/*
 * Created on 2006-4-20 12:12:48
 */
package cn.com.sbell.vss.csg.vsclient.hikvision;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import cn.com.sbell.vss.csg.vap.bean.AlarmConfiguration;
import cn.com.sbell.vss.csg.vap.bean.CameraHide;
import cn.com.sbell.vss.csg.vap.bean.CruisePointInfo;
import cn.com.sbell.vss.csg.vap.bean.CruiseTrackInfo;
import cn.com.sbell.vss.csg.vap.bean.DeviceStatistic;
import cn.com.sbell.vss.csg.vap.bean.DiskSizeInfo;
import cn.com.sbell.vss.csg.vap.bean.GPIODeviceInfo;
import cn.com.sbell.vss.csg.vap.bean.ImageAdjustingInfo;
import cn.com.sbell.vss.csg.vap.bean.ImageParameterInfos;
import cn.com.sbell.vss.csg.vap.bean.LocalStorageTask;
import cn.com.sbell.vss.csg.vap.bean.NetManageInfo;
import cn.com.sbell.vss.csg.vap.bean.NetworkCfgIn;
import cn.com.sbell.vss.csg.vap.bean.NetworkCfgOut;
import cn.com.sbell.vss.csg.vap.bean.PTZRegress;
import cn.com.sbell.vss.csg.vap.bean.PresetPTZ;
import cn.com.sbell.vss.csg.vap.bean.PtzCommander;
import cn.com.sbell.vss.csg.vap.bean.RecordFile;
import cn.com.sbell.vss.csg.vap.bean.RecordSchedule;
import cn.com.sbell.vss.csg.vap.bean.Schedule;
import cn.com.sbell.vss.csg.vap.bean.SerialPortInfo;
import cn.com.sbell.vss.csg.vap.bean.StorageQuery;
import cn.com.sbell.vss.csg.vap.bean.TimeInfo;
import cn.com.sbell.vss.csg.vap.bean.TransparentChannelInfo;
import cn.com.sbell.vss.csg.vap.bean.UploadPic;
import cn.com.sbell.vss.csg.vap.bean.UserInfo;
import cn.com.sbell.vss.csg.vap.bean.VSCommon;
import cn.com.sbell.vss.csg.vap.bean.VideoFormat;
import cn.com.sbell.vss.csg.vap.bean.VideoInfo;
import cn.com.sbell.vss.csg.vap.bean.VideoPerformance;
import cn.com.sbell.vss.csg.vap.bean.GPIODeviceInfo.ChannelInfo;
import cn.com.sbell.vss.csg.vap.bean.ImageParameterInfos.ImageParameterInfo;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.AlarmInCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.AlarmOutCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.AlarmOutState;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.CompressionCfgEx;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.CompressionInfoEx;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.CruiseCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.CruiseCountCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.CruisePoint;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.DecoderCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.DeviceCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.DeviceInfo;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.ExceptionCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.FrontIdCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.HideImageArea;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.HideImageAreaCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.ImageFormat;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.JPEGCFG;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.JPEGPARA;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.LocalStorageFile;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.ManageCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.NetCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.PPPoEConf;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.PTZResetCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.PicCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.RS232Cfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.RecordAllDay;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.RecordCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.RecordSched;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.RecordStatus;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.ResourceUsedInfo;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.SchedTime;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.SerialMessageInfo;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.TimeCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.UserCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.VsCommonInfo;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.WorkState;

public class HikVisionDVRClient {
    private String vsIp;
    private Integer vsPort;
    private String vsLoginUsername;
    private String vsLoginPassword;
    private String vsVendor;
    private String vsProductVersion;
    private String vsSoftwareVersion;
    private String vsUserId;
    private String vsDeviceId;
    private String vsFrontType;

	/* CONSTANTS */
	public final static int IMAGE_NET_PARAM = 0;

	public final static int IMAGE_REC_PARAM = 1;

	public static final String CHARSET = "GB2312";

	private static Map CLIENT_MAP = new HashMap();

	private static Map DEVICE_MAP = new HashMap();

	static {
		CLIENT_MAP.put("DCIF", new Integer(0));
		CLIENT_MAP.put("CIF", new Integer(1));
		CLIENT_MAP.put("QCIF", new Integer(2));
		CLIENT_MAP.put("4CIF", new Integer(3));
		CLIENT_MAP.put("2CIF", new Integer(4));
		CLIENT_MAP.put("QSIF", new Integer(5));
		CLIENT_MAP.put("SIF", new Integer(6));
		CLIENT_MAP.put("4SIF/VGA", new Integer(7));
		CLIENT_MAP.put("QVGA", new Integer(6));// qvga use 6, sif no use, add in
												// ct EVDO

		DEVICE_MAP.put(new Integer(0), "DCIF");
		DEVICE_MAP.put(new Integer(1), "CIF");
		DEVICE_MAP.put(new Integer(2), "QCIF");
		DEVICE_MAP.put(new Integer(3), "4CIF");
		DEVICE_MAP.put(new Integer(4), "2CIF");
		DEVICE_MAP.put(new Integer(5), "QSIF");
		// QVGA for imageParam_3N
		DEVICE_MAP.put(new Integer(6), "SIF");
		DEVICE_MAP.put(new Integer(7), "4SIF/VGA");

	}

	// private static Map loginInfoCache = Collections.synchronizedMap(new
	// HashMap());

	/* FIELDS */

	public DeviceInfo deviceInfo;
	public int userId = -1;

	public HikVisionDVRClient() {
		this.vsIp = "192.168.6.72";
		this.vsPort = 8000;
		this.vsLoginUsername = "admin";
		this.vsLoginPassword = "12345";
		this.vsVendor = "Hikvision";
		this.vsProductVersion = "DS-7608N-ST";
		this.vsSoftwareVersion = "V2.2.2  build 120924";
		this.vsUserId = "7147B67E2D29FE74A4311C9357B7A408";
		this.vsDeviceId = "000000000103520002";
		this.vsFrontType = "VS";
	}

	public void init() {
		System.out.println("Connecting to " + this.vsIp + ":" + this.vsPort + " ...");
		deviceInfo = new DeviceInfo();
		userId = HcNetAdapter.login(this.vsIp, this.vsPort.intValue(),
				this.vsLoginUsername, this.vsLoginPassword, deviceInfo);
		if (userId < 0) {
			System.out.println("HcNetAdapter.login failed...");
		}
		System.out.println("Connected to " + this.vsIp + ":" + this.vsPort + " successfully! USERID:" + userId);
	}

	public void close() {
		if (userId >= 0) {
			HcNetAdapter.logout(userId);
		}
	}

	public int getLastStatusCode() {
		return HcNetAdapter.getLastStatusCode();
	}

	public boolean controlPtz(PtzCommander ptzCmder) {
		boolean bRes = false;
		int channel = ptzCmder.getPtzId().intValue();
		int command = HikVisionPtzCommandSet.getPtzCommand(ptzCmder.getCmd());
		int speed = ptzCmder.getSpeed() == null ? 0 : ptzCmder.getSpeed()
				.intValue();
		switch (command) {
		case 39: // GO TO Preset
			int presetId = new Integer(ptzCmder.getParam()).intValue();
			bRes = HcNetAdapter.ptzPreset(userId, channel, command, presetId);
			break;
		case -1: // STOP
			int previousCmd = HikVisionPtzCommandSet.getPtzCommand(ptzCmder
					.getParam());
			if (-1 == previousCmd) {
				bRes = true;
				break;
			}
			bRes = HcNetAdapter.controlPtzWithSpeed(userId, channel,
					previousCmd, 1, speed);
			break;
		case 37:// START_TRACK_CRUISE
			int cruiseNum_toStart = new Integer(ptzCmder.getParam()).intValue();
			bRes = HcNetAdapter.startPTZCruise(userId, channel,
					cruiseNum_toStart);
			break;
		case 38:// STOP_TRACK_CRUISE
			int cruiseNum_toStop = new Integer(ptzCmder.getParam()).intValue();
			bRes = HcNetAdapter
					.stopPTZCruise(userId, channel, cruiseNum_toStop);
			break;
		default:
			bRes = HcNetAdapter.controlPtzWithSpeed(userId, channel, command,
					0, speed);
		}

		return bRes;
	}

	public boolean controlVs(int action) {
		boolean bRes;
		switch (action) {
		case 0:
			bRes = HcNetAdapter.reboot(userId);
			userId = -1; // set this userid invalid
			break;
		case 1:
			bRes = HcNetAdapter.shutdown(userId);
			userId = -1; // set this userid invalid
			break;
		default:
			bRes = false;
		}
		return bRes;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.com.sbell.vss.csg.vsclient.VsClient#setNetworkInfo(cn.com.sbell.vss
	 * .csg.vap.bean.NetworkInfo)
	 */
	public boolean setNetworkInfo(NetworkCfgIn networkInfo) {
		NetCfg netCfg = new NetCfg();
		if (!HcNetAdapter.getNetCfg(userId, 0, netCfg)) {
			return false;
		}

		int netIndex = networkInfo.getNetId().intValue() - 1;
		netCfg.ethernet[netIndex].ipAddress = networkInfo.getIpAddress();
		netCfg.ethernet[netIndex].netMask = networkInfo.getSubnetMask();
		netCfg.ethernet[netIndex].port = networkInfo.getPort().intValue();
		String[] dns = networkInfo.getDns();
		if (dns != null && dns.length > 0 && dns[0] != null) {
			netCfg.dns = dns[0];
		}
		String[] gateway = networkInfo.getGateway();
		if (gateway != null && gateway.length > 0 && gateway[0] != null) {
			netCfg.gateway = gateway[0];
		}
		boolean isNetCfgOk = HcNetAdapter.setNetCfg(userId, 0, netCfg);
		if (isNetCfgOk) {
			boolean isControlOk = this.controlVs(0);
			System.out.println("Reboot is " + isControlOk + " after setNetworkInfo.");
		}
		return isNetCfgOk;
	}

	public NetworkCfgOut getNetworkInfo() {
		NetCfg netCfg = new NetCfg();
		if (!HcNetAdapter.getNetCfg(userId, 0, netCfg)) {
			System.out.println("HcNetAdapter.getNetCfg failed...");
		}

		NetworkCfgOut networkInfo = new NetworkCfgOut();
		NetworkCfgOut.Ethernet[] ethernets = new NetworkCfgOut.Ethernet[netCfg.ethernet.length];
		for (int i = 0; i < ethernets.length; i++) {
			NetworkCfgOut.Ethernet ethernet = new NetworkCfgOut.Ethernet();
			ethernet.setNetId(new Integer(i + 1));
			ethernet.setIpAddress(netCfg.ethernet[i].ipAddress);
			ethernet.setNetMask(netCfg.ethernet[i].netMask);
			ethernet.setPort(new Integer(netCfg.ethernet[i].port));
			ethernets[i] = ethernet;
		}
		networkInfo.setEthernet(ethernets);
		networkInfo.setDns(new String[] { netCfg.dns });
		networkInfo.setGateway(new String[] { netCfg.gateway });

		return networkInfo;
	}

	public boolean setUser(UserInfo userInfo) {
		UserCfg userCfg = new UserCfg();
		if (!HcNetAdapter.getUserCfg(userId, 0, userCfg)) {
			return false;
		}
		int i = 0;
		for (; i < userCfg.users.length; i++) {
			if ("".equals(userCfg.users[i].username)
					|| userInfo.getName().equals(userCfg.users[i].username)) {
				break;
			}
		}
		if (i > 15) {
			return false; // Max only support 16 users
		}
		userCfg.users[i].username = userInfo.getName();
		userCfg.users[i].password = userInfo.getPassword();
		return HcNetAdapter.setUserCfg(userId, 0, userCfg);
	}

	public UserInfo[] getUser(String username) {
		UserCfg userCfg = new UserCfg();
		if (!HcNetAdapter.getUserCfg(userId, 0, userCfg)) {
			System.out.println("HcNetAdapter.getUserCfg failed...");
		}
		List userList = new ArrayList();
		for (int i = 0; i < userCfg.users.length; i++) {
			if ("".equals(userCfg.users[i].username)) {
				continue;
			}
			UserInfo user = new UserInfo();
			user.setName(userCfg.users[i].username);
			user.setPassword(userCfg.users[i].password);
			userList.add(user);
		}
		return (UserInfo[]) userList.toArray(new UserInfo[0]);
	}

	public boolean deleteUser(String username) {
		UserCfg userCfg = new UserCfg();
		if (!HcNetAdapter.getUserCfg(userId, 0, userCfg)) {
			return false;
		}
		for (int i = 0; i < userCfg.users.length; i++) {
			if (username.equals(userCfg.users[i].username)) {
				userCfg.users[i].username = "";
				userCfg.users[i].password = "";
			}
		}
		return HcNetAdapter.setUserCfg(userId, 0, userCfg);
	}

	public boolean setSerialPortInfo(SerialPortInfo serialPortInfo) {
		// Set serial port
		RS232Cfg rs232Cfg = new RS232Cfg();
		if (!HcNetAdapter.getRS232Cfg(userId, serialPortInfo.getPort()
				.intValue(), rs232Cfg)) {
			return false;
		}
		// hik SDK changed, baudrate
		rs232Cfg.baudRate = serialPortInfo.getBaudRate().intValue();
		// hik SDK changed
		// rs232Cfg.dataBit = serialPortInfo.getDataBit().intValue() - 5;
		rs232Cfg.dataBit = serialPortInfo.getDataBit().intValue();
		if (null != serialPortInfo.getFlowcontrol()) {
			rs232Cfg.flowControl = serialPortInfo.getFlowcontrol().intValue();
		}
		rs232Cfg.parity = serialPortInfo.getParity().intValue();
		// hik SDK changed
		// rs232Cfg.stopBit = serialPortInfo.getStopBit().intValue() - 1;
		rs232Cfg.stopBit = serialPortInfo.getStopBit().intValue();
		if (null != serialPortInfo.getWorkMode()) {
			rs232Cfg.workMode = serialPortInfo.getWorkMode().intValue();
		}
		return HcNetAdapter.setRS232Cfg(userId, serialPortInfo.getPort()
				.intValue(), rs232Cfg);
	}

	public SerialPortInfo getSerialPortInfo(int port) {
		RS232Cfg rs232Cfg = new RS232Cfg();
		if (!HcNetAdapter.getRS232Cfg(userId, port, rs232Cfg)) {
			System.out.println("HcNetAdapter.getRS232Cfg failed...");
		}

		SerialPortInfo serialPortInfo = new SerialPortInfo();
		// hik SDK changed baudrate
		serialPortInfo.setBaudRate(new Integer(rs232Cfg.baudRate));
		// hik SDK changed
		// serialPortInfo.setDataBit(new Integer(rs232Cfg.dataBit + 5));
		serialPortInfo.setDataBit(new Integer(rs232Cfg.dataBit));
		serialPortInfo.setFlowcontrol(new Integer(rs232Cfg.flowControl));
		serialPortInfo.setParity(new Integer(rs232Cfg.parity));
		serialPortInfo.setPort(new Integer(port));
		// hik SDK changed
		// serialPortInfo.setStopBit(new Integer(rs232Cfg.stopBit + 1));
		serialPortInfo.setStopBit(new Integer(rs232Cfg.stopBit));
		serialPortInfo.setWorkMode(new Integer(rs232Cfg.workMode));

		return serialPortInfo;
	}

	public boolean setVideoInfo(VideoInfo videoInfo) {
		PicCfg picCfg = new PicCfg();
		if (!HcNetAdapter.getPicCfg(userId, videoInfo.getVideoId().intValue(),
				picCfg)) {
			return false;
		}

		try {
			picCfg.channelName = videoInfo.getBitmapText().getBytes(HikVisionDVRClient.CHARSET);
		} catch (UnsupportedEncodingException e) {
			System.out.println("Encode channelName error" + e);
		}
		picCfg.OSDTopLeftX = videoInfo.getBitmapX().intValue();
		picCfg.OSDTopLeftY = videoInfo.getBitmapY().intValue();
		picCfg.showChanName = videoInfo.getBitmapTextEnable().intValue();
		if (videoInfo.getBitmapTextX() != null) {
			picCfg.showNameTopLeftX = videoInfo.getBitmapTextX().intValue();
		}
		if (videoInfo.getBitmapTextY() != null) {
			picCfg.showNameTopLeftY = videoInfo.getBitmapTextY().intValue();
		}
		picCfg.showOsd = videoInfo.getBitmapTimeEnable().intValue();
		try {
			System.out.println("chinese name: gb2312 ["
					+ Arrays.toString(videoInfo.getBitmapText().getBytes(
							"gb2312"))
					+ "],utf-8 ["
					+ Arrays.toString(videoInfo.getBitmapText().getBytes(
							"utf-8")) + "]"
					+ Arrays.toString(picCfg.channelName) + "");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return HcNetAdapter.setPicCfg(userId,
				videoInfo.getVideoId().intValue(), picCfg);
	}

	public VideoInfo getVideoInfo(int videoId) {
		PicCfg picCfg = new PicCfg();
		if (!HcNetAdapter.getPicCfg(userId, videoId, picCfg)) {
			System.out.println("HcNetAdapter.getPicCfg failed...");
		}

		VideoInfo videoInfo = new VideoInfo();
		videoInfo.setVideoId(new Integer(videoId));
		try {
			videoInfo.setBitmapText(new String(picCfg.channelName,
					HikVisionDVRClient.CHARSET));
		} catch (UnsupportedEncodingException e) {
			System.out.println("Decode channelName error" + e);
		}
		videoInfo.setBitmapTextEnable(new Integer(picCfg.showChanName));
		videoInfo.setBitmapTextX(new Integer(picCfg.showNameTopLeftX));
		videoInfo.setBitmapTextY(new Integer(picCfg.showNameTopLeftY));
		videoInfo.setBitmapTimeEnable(new Integer(picCfg.showOsd));
		videoInfo.setBitmapX(new Integer(picCfg.OSDTopLeftX));
		videoInfo.setBitmapY(new Integer(picCfg.OSDTopLeftY));
		System.out.println("chinese:[" + Arrays.toString(picCfg.channelName) + "]");
		return videoInfo;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.com.sbell.vss.csg.vsclient.VsClient#setImageAdjustingInfo(cn.com.sbell
	 * .vss.csg.vap.bean.ImageAdjustingInfo)
	 */
	public boolean setImageAdjustingInfo(ImageAdjustingInfo imgInfo) {
		PicCfg picCfg = new PicCfg();
		if (!HcNetAdapter.getPicCfg(userId, imgInfo.getVideoId().intValue(),
				picCfg)) {
			return false;
		}

		picCfg.brightness = imgInfo.getBright().intValue();
		picCfg.constrast = imgInfo.getContrast().intValue();
		picCfg.hue = imgInfo.getHue().intValue();
		picCfg.saturation = imgInfo.getSaturation().intValue();

		return HcNetAdapter.setPicCfg(userId, imgInfo.getVideoId().intValue(),
				picCfg);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.com.sbell.vss.csg.vsclient.VsClient#getImageAdjustingInfo(int)
	 */
	public ImageAdjustingInfo getImageAdjustingInfo(int videoId) {
		PicCfg picCfg = new PicCfg();
		if (!HcNetAdapter.getPicCfg(userId, videoId, picCfg)) {
		}

		ImageAdjustingInfo imgInfo = new ImageAdjustingInfo();
		imgInfo.setVideoId(new Integer(videoId));
		imgInfo.setBright(new Integer(picCfg.brightness));
		imgInfo.setContrast(new Integer(picCfg.constrast));
		imgInfo.setHue(new Integer(picCfg.hue));
		imgInfo.setSaturation(new Integer(picCfg.saturation));

		return imgInfo;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.com.sbell.vss.csg.vsclient.VsClient#setImageFormat(java.lang.String)
	 */
	public boolean setImageFormat(VideoFormat fmtInfo) {
		return false;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.com.sbell.vss.csg.vsclient.VsClient#getImageFormat(int)
	 */
	public VideoFormat getImageFormat(int videoId) {
		VideoFormat vf = new VideoFormat();
		vf.setMode("H264");
		return vf;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.com.sbell.vss.csg.vsclient.VsClient#setTime(cn.com.sbell.vss.csg.vap
	 * .bean.TimeInfo)
	 */
	public boolean setTime(TimeInfo timeInfo) {
		TimeCfg timeCfg = new TimeCfg();
		timeCfg.date = timeInfo.getDate().intValue();
		timeCfg.hour = timeInfo.getHour().intValue();
		timeCfg.minute = timeInfo.getMinute().intValue();
		timeCfg.month = timeInfo.getMonth().intValue();
		timeCfg.second = timeInfo.getSecond().intValue();
		timeCfg.year = timeInfo.getYear().intValue();

		return HcNetAdapter.setTimeCfg(userId, 0, timeCfg);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.com.sbell.vss.csg.vsclient.VsClient#getTime()
	 */
	public TimeInfo getTime() {
		TimeCfg timeCfg = new TimeCfg();
		if (!HcNetAdapter.getTimeCfg(userId, 0, timeCfg)) {
		}

		TimeInfo timeInfo = new TimeInfo();
		timeInfo.setDate(new Integer(timeCfg.date));
		timeInfo.setHour(new Integer(timeCfg.hour));
		timeInfo.setMinute(new Integer(timeCfg.minute));
		timeInfo.setMonth(new Integer(timeCfg.month));
		timeInfo.setSecond(new Integer(timeCfg.second));
		timeInfo.setYear(new Integer(timeCfg.year));

		return timeInfo;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.com.sbell.vss.csg.vsclient.VsClient#setInOutDev(cn.com.sbell.vss.csg
	 * .vap.bean.GPIODeviceInfo.ChannelInfo)
	 */
	public boolean setInOutDev(ChannelInfo channelInfo) {
		int channelNumber = channelInfo.getChannelNumber().intValue() - 1;
		int state = channelInfo.getState().intValue() == 0 ? 0 : 1;
		boolean bRes = false;
		if (channelInfo.getChannelType() == GPIODeviceInfo.INPUT) {
			AlarmInCfg alarmInCfg = new AlarmInCfg();
			if (!HcNetAdapter.getAlarmInCfg(userId, channelNumber, alarmInCfg)) {
				return false;
			} else {
				alarmInCfg.state = state;
				bRes = HcNetAdapter.setAlarmInCfg(userId, channelNumber,
						alarmInCfg);
			}
		} else {
			bRes = HcNetAdapter.setAlarmOut(userId, channelNumber, state);
		}

		return bRes;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.com.sbell.vss.csg.vsclient.VsClient#getInOutDev()
	 */
	public GPIODeviceInfo getInOutDev() {
		ChannelInfo[] input = new ChannelInfo[deviceInfo.alarmInPortNum];
		AlarmInCfg alarmIn = new AlarmInCfg();
		for (int i = 0; i < input.length; i++) {
			if (!HcNetAdapter.getAlarmInCfg(userId, i, alarmIn)) {
			}
			ChannelInfo channInfo = new ChannelInfo();
			channInfo.setChannelNumber(new Integer(i + 1));
			channInfo.setState(new Integer(alarmIn.state));
			input[i] = channInfo;
		}
		ChannelInfo[] output = new ChannelInfo[deviceInfo.alarmOutPortNum];
		AlarmOutState outState = new AlarmOutState();
		if (!HcNetAdapter.getAlarmOut(userId, outState)) {
		}

		for (int i = 0; i < output.length; i++) {
			ChannelInfo channInfo = new ChannelInfo();
			channInfo.setChannelNumber(new Integer(i + 1));
			channInfo.setState(new Integer(outState.state[i]));
			output[i] = channInfo;
		}
		GPIODeviceInfo gpioDevInfo = new GPIODeviceInfo();
		gpioDevInfo.setInput(input);
		gpioDevInfo.setOutput(output);

		return gpioDevInfo;
	}

	public boolean setPresetPTZ(PresetPTZ preset) {
		int command = 8;
		String presetName = preset.getPresetName();
		if (presetName == null || presetName.equals("")) {
			// Delete
			command = 9;
		}
		return HcNetAdapter.ptzPreset(userId, preset.getPtzId().intValue(),
				command, preset.getPresetIndex().intValue());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.com.sbell.vss.csg.vsclient.VsClient#getPresetPTZ(int)
	 */
	public PresetPTZ[] getPresetPTZ(int ptzId) {
		DecoderCfg decoderCfg = new DecoderCfg();
		if (!HcNetAdapter.getDecoderCfg(userId, ptzId, decoderCfg)) {
		}
		ArrayList ptzList = new ArrayList();
		for (int i = 0; i < decoderCfg.setPreset.length; i++) {
			if (decoderCfg.setPreset[i] == 1) {
				PresetPTZ ptz = new PresetPTZ();
				ptz.setPtzId(new Integer(ptzId));
				ptz.setPresetIndex(new Integer(i + 1));
				ptzList.add(ptz);
			}
		}
		return (PresetPTZ[]) ptzList.toArray(new PresetPTZ[0]);
	}

	public boolean setImageParameterInfo(ImageParameterInfo imgParam) {
		CompressionCfgEx compressionCfgEx = new CompressionCfgEx();
		if (!HcNetAdapter.getCompressionCfgEx(userId, imgParam.getVideoId()
				.intValue(), compressionCfgEx)) {
			return false;
		}
		// hik sdk changed, just use input value
		// int bitRate = getHcBitRate(imgParam.getBitRate().intValue());
		int bitRate = imgParam.getBitRate().intValue();
		// hik sdk changed
		// int frameRate = getHcFrameRate(imgParam.getFrameRate().intValue());
		int frameRate = imgParam.getFrameRate().intValue();
		System.out.println("bitRate:" + bitRate + ",frameRate:" + frameRate);
		if (imgParam.getFlag() == null)
			imgParam.setFlag(new Integer(0));
		switch (imgParam.getFlag().intValue() % 2) {
		case IMAGE_NET_PARAM:
			compressionCfgEx.netParam.bitRate = bitRate;
			if (imgParam.getBitRateType() != null) {
				compressionCfgEx.netParam.bitRateType = imgParam
						.getBitRateType().intValue();
			}
			compressionCfgEx.netParam.frameRate = frameRate;
			compressionCfgEx.netParam.imageSize = ((Integer) CLIENT_MAP
					.get(imgParam.getImageSize().toUpperCase())).intValue();
			if (null != imgParam.getPicQuality()) {
				compressionCfgEx.netParam.picQuality = imgParam.getPicQuality()
						.intValue();
			}
			compressionCfgEx.netParam.iFrameInterval = imgParam
					.getIFrameInterval().intValue();
			if (null != imgParam.getStreamType()) {
				compressionCfgEx.netParam.streamType = imgParam.getStreamType()
						.intValue();
			}
			break;
		case IMAGE_REC_PARAM:
			compressionCfgEx.recordParam.bitRate = bitRate;
			if (imgParam.getBitRateType() != null) {
				compressionCfgEx.recordParam.bitRateType = imgParam
						.getBitRateType().intValue();
			}
			compressionCfgEx.recordParam.frameRate = frameRate;
			compressionCfgEx.recordParam.imageSize = ((Integer) CLIENT_MAP
					.get(imgParam.getImageSize().toUpperCase())).intValue();
			if (null != imgParam.getPicQuality()) {
				compressionCfgEx.recordParam.picQuality = imgParam
						.getPicQuality().intValue();
			}
			compressionCfgEx.recordParam.iFrameInterval = imgParam
					.getIFrameInterval().intValue();
			if (null != imgParam.getStreamType()) {
				compressionCfgEx.recordParam.streamType = imgParam
						.getStreamType().intValue();
			}
			break;
		}

		return HcNetAdapter.setCompressionCfgEx(userId, imgParam.getVideoId()
				.intValue(), compressionCfgEx);

	}

	public ImageParameterInfos getImageParameterInfo(int videoId) {
		CompressionCfgEx compressionCfgEx = new CompressionCfgEx();
		if (!HcNetAdapter
				.getCompressionCfgEx(userId, videoId, compressionCfgEx)) {
		}

		ImageParameterInfos imgParams = new ImageParameterInfos();
		ImageParameterInfo netImgParam = new ImageParameterInfo();
		netImgParam.setVideoId(new Integer(videoId));
		netImgParam.setFlag(new Integer(IMAGE_NET_PARAM));
		// hik SDK changed
		// netImgParam.setBitRate(new Integer(
		// getVapBitRate(compressionCfgEx.netParam.bitRate)));
		netImgParam.setBitRate(new Integer(compressionCfgEx.netParam.bitRate));
		netImgParam.setBitRateType(new Integer(
				compressionCfgEx.netParam.bitRateType));
		// hik SDK changed
		// netImgParam.setFrameRate(new Integer(
		// getVapFrameRate(compressionCfgEx.netParam.frameRate)));
		netImgParam.setFrameRate(new Integer(
				compressionCfgEx.netParam.frameRate));
		netImgParam.setImageSize(DEVICE_MAP.get(
				new Integer(compressionCfgEx.netParam.imageSize)).toString());
		// if(compressionCfgEx.netParam.imageSize==6){
		// netImgParam.setImageSize("SIF");
		// }
		netImgParam.setPicQuality(new Integer(
				compressionCfgEx.netParam.picQuality));
		netImgParam.setIFrameInterval(new Integer(
				compressionCfgEx.netParam.iFrameInterval));
		netImgParam.setStreamType(new Integer(
				compressionCfgEx.netParam.streamType));
		imgParams.setNets(new ImageParameterInfo[] { netImgParam });
		ImageParameterInfo recImgParam = new ImageParameterInfo();
		recImgParam.setVideoId(new Integer(videoId));
		recImgParam.setFlag(new Integer(IMAGE_REC_PARAM));
		// hik SDK changed
		// recImgParam.setBitRate(new Integer(
		// getVapBitRate(compressionCfgEx.recordParam.bitRate)));
		recImgParam
				.setBitRate(new Integer(compressionCfgEx.recordParam.bitRate));
		recImgParam.setBitRateType(new Integer(
				compressionCfgEx.recordParam.bitRateType));
		// hik SDK changed
		// recImgParam.setFrameRate(new Integer(
		// getVapFrameRate(compressionCfgEx.recordParam.frameRate)));
		recImgParam.setFrameRate(new Integer(
				compressionCfgEx.recordParam.frameRate));
		recImgParam
				.setImageSize(DEVICE_MAP.get(
						new Integer(compressionCfgEx.recordParam.imageSize))
						.toString());
		// if(compressionCfgEx.recordParam.imageSize==6){
		// recImgParam.setImageSize("QVGA");
		// }
		recImgParam.setPicQuality(new Integer(
				compressionCfgEx.recordParam.picQuality));
		recImgParam.setIFrameInterval(new Integer(
				compressionCfgEx.recordParam.iFrameInterval));
		recImgParam.setStreamType(new Integer(
				compressionCfgEx.recordParam.streamType));
		imgParams.setRec(recImgParam);

		return imgParams;
	}

	public boolean setImageParameterInfo_3N(ImageParameterInfo imgParam) {
		CompressionCfgEx compressionCfgEx = new CompressionCfgEx();
		if (!HcNetAdapter.getCompressionCfgEx_3N(userId, imgParam.getVideoId()
				.intValue(), compressionCfgEx)) {
			return false;
		}
		// hik sdk changed, just use input value
		// int bitRate = getHcBitRate(imgParam.getBitRate().intValue());
		int bitRate = imgParam.getBitRate().intValue();
		// hik sdk changed
		// int frameRate = getHcFrameRate(imgParam.getFrameRate().intValue());
		int frameRate = imgParam.getFrameRate().intValue();
		System.out.println("bitRate:" + bitRate + ",frameRate:" + frameRate);
		switch (imgParam.getFlag()) {
		case IMAGE_NET_PARAM:
			CompressionInfoEx netParam = null;
			switch (imgParam.getSubStreamId()) {
			case 1:
				netParam = compressionCfgEx.netParam1;
				break;
			case 2:
				netParam = compressionCfgEx.netParam2;
				break;
			case 3:
				netParam = compressionCfgEx.netParam3;
				break;
			default:
				System.out.println("unsupported substreamid= "
						+ imgParam.getSubStreamId());
				return false;
			}
			netParam.bitRate = bitRate;
			if (imgParam.getBitRateType() != null) {
				netParam.bitRateType = imgParam.getBitRateType().intValue();
			}
			netParam.frameRate = frameRate;
			netParam.imageSize = ((Integer) CLIENT_MAP.get(imgParam
					.getImageSize().toUpperCase())).intValue();
			if (null != imgParam.getPicQuality()) {
				netParam.picQuality = imgParam.getPicQuality().intValue();
			}
			netParam.iFrameInterval = imgParam.getIFrameInterval().intValue();
			if (null != imgParam.getStreamType()) {
				netParam.streamType = imgParam.getStreamType().intValue();
			}
			break;
		case IMAGE_REC_PARAM:
			compressionCfgEx.recordParam.bitRate = bitRate;
			if (imgParam.getBitRateType() != null) {
				compressionCfgEx.recordParam.bitRateType = imgParam
						.getBitRateType().intValue();
			}
			compressionCfgEx.recordParam.frameRate = frameRate;
			compressionCfgEx.recordParam.imageSize = ((Integer) CLIENT_MAP
					.get(imgParam.getImageSize().toUpperCase())).intValue();
			if (null != imgParam.getPicQuality()) {
				compressionCfgEx.recordParam.picQuality = imgParam
						.getPicQuality().intValue();
			}
			compressionCfgEx.recordParam.iFrameInterval = imgParam
					.getIFrameInterval().intValue();
			if (null != imgParam.getStreamType()) {
				compressionCfgEx.recordParam.streamType = imgParam
						.getStreamType().intValue();
			}
			break;
		}

		return HcNetAdapter.setCompressionCfgEx_3N(userId, imgParam
				.getVideoId().intValue(), compressionCfgEx);

	}

	public ImageParameterInfos getImageParameterInfo_3N(int videoId) {
		CompressionCfgEx compressionCfgEx = new CompressionCfgEx();
		if (!HcNetAdapter.getCompressionCfgEx_3N(userId, videoId,
				compressionCfgEx)) {
		}

		ImageParameterInfos imgParams = new ImageParameterInfos();
		ImageParameterInfo[] netParams = new ImageParameterInfo[3];
		// netParam1
		ImageParameterInfo netImgParam = new ImageParameterInfo();
		netImgParam.setVideoId(new Integer(videoId));
		netImgParam.setFlag(new Integer(IMAGE_NET_PARAM));
		netImgParam.setSubStreamId(new Integer(1));
		netImgParam.setBitRate(new Integer(compressionCfgEx.netParam1.bitRate));
		netImgParam.setBitRateType(new Integer(
				compressionCfgEx.netParam1.bitRateType));
		netImgParam.setFrameRate(new Integer(
				compressionCfgEx.netParam1.frameRate));
		netImgParam.setImageSize(DEVICE_MAP.get(
				new Integer(compressionCfgEx.netParam1.imageSize)).toString());
		if (compressionCfgEx.netParam1.imageSize == 6) {
			netImgParam.setImageSize("QVGA");
		}
		netImgParam.setPicQuality(new Integer(
				compressionCfgEx.netParam1.picQuality));
		netImgParam.setIFrameInterval(new Integer(
				compressionCfgEx.netParam1.iFrameInterval));
		netImgParam.setStreamType(new Integer(
				compressionCfgEx.netParam1.streamType));
		netParams[0] = netImgParam;
		// netParam2
		netImgParam = new ImageParameterInfo();
		netImgParam.setVideoId(new Integer(videoId));
		netImgParam.setFlag(new Integer(IMAGE_NET_PARAM));
		netImgParam.setSubStreamId(new Integer(2));
		netImgParam.setBitRate(new Integer(compressionCfgEx.netParam2.bitRate));
		netImgParam.setBitRateType(new Integer(
				compressionCfgEx.netParam2.bitRateType));
		netImgParam.setFrameRate(new Integer(
				compressionCfgEx.netParam2.frameRate));
		netImgParam.setImageSize(DEVICE_MAP.get(
				new Integer(compressionCfgEx.netParam2.imageSize)).toString());
		if (compressionCfgEx.netParam2.imageSize == 6) {
			netImgParam.setImageSize("QVGA");
		}
		netImgParam.setPicQuality(new Integer(
				compressionCfgEx.netParam2.picQuality));
		netImgParam.setIFrameInterval(new Integer(
				compressionCfgEx.netParam2.iFrameInterval));
		netImgParam.setStreamType(new Integer(
				compressionCfgEx.netParam2.streamType));
		netParams[1] = netImgParam;

		// netParam3
		netImgParam = new ImageParameterInfo();
		netImgParam.setVideoId(new Integer(videoId));
		netImgParam.setFlag(new Integer(IMAGE_NET_PARAM));
		netImgParam.setSubStreamId(new Integer(3));
		netImgParam.setBitRate(new Integer(compressionCfgEx.netParam3.bitRate));
		netImgParam.setBitRateType(new Integer(
				compressionCfgEx.netParam3.bitRateType));
		netImgParam.setFrameRate(new Integer(
				compressionCfgEx.netParam3.frameRate));
		netImgParam.setImageSize(DEVICE_MAP.get(
				new Integer(compressionCfgEx.netParam3.imageSize)).toString());
		if (compressionCfgEx.netParam3.imageSize == 6) {
			netImgParam.setImageSize("QVGA");
		}
		netImgParam.setPicQuality(new Integer(
				compressionCfgEx.netParam3.picQuality));
		netImgParam.setIFrameInterval(new Integer(
				compressionCfgEx.netParam3.iFrameInterval));
		netImgParam.setStreamType(new Integer(
				compressionCfgEx.netParam3.streamType));
		netParams[2] = netImgParam;
		imgParams.setNets(netParams);

		ImageParameterInfo recImgParam = new ImageParameterInfo();
		recImgParam.setVideoId(new Integer(videoId));
		recImgParam.setFlag(new Integer(IMAGE_REC_PARAM));
		recImgParam
				.setBitRate(new Integer(compressionCfgEx.recordParam.bitRate));
		recImgParam.setBitRateType(new Integer(
				compressionCfgEx.recordParam.bitRateType));
		recImgParam.setFrameRate(new Integer(
				compressionCfgEx.recordParam.frameRate));
		recImgParam
				.setImageSize(DEVICE_MAP.get(
						new Integer(compressionCfgEx.recordParam.imageSize))
						.toString());
		if (compressionCfgEx.recordParam.imageSize == 6) {
			recImgParam.setImageSize("QVGA");
		}
		recImgParam.setPicQuality(new Integer(
				compressionCfgEx.recordParam.picQuality));
		recImgParam.setIFrameInterval(new Integer(
				compressionCfgEx.recordParam.iFrameInterval));
		recImgParam.setStreamType(new Integer(
				compressionCfgEx.recordParam.streamType));
		imgParams.setRec(recImgParam);

		return imgParams;
	}

	public SerialPortInfo getDecoderCfg(
	// int decoderAddress
			int videoId) {
		DecoderCfg decoderCfg = new DecoderCfg();
		if (!HcNetAdapter.getDecoderCfg(userId,
		// decoderAddress,
				videoId, decoderCfg)) {
		}

		SerialPortInfo serialPortInfo = new SerialPortInfo();
		// hik SDK changed, baudrate
		// serialPortInfo.setBaudRate(new Integer(
		// getVapBaudRate(decoderCfg.baudRate)));
		serialPortInfo.setBaudRate(new Integer(decoderCfg.baudRate));
		// hik SDK changed
		// serialPortInfo.setDataBit(new Integer(decoderCfg.dataBit + 5));
		serialPortInfo.setDataBit(new Integer(decoderCfg.dataBit));
		serialPortInfo.setFlowcontrol(new Integer(decoderCfg.flowControl));
		serialPortInfo.setParity(new Integer(decoderCfg.parity));
		// hik SDK changed
		// serialPortInfo.setStopBit(new Integer(decoderCfg.stopBit + 1));
		serialPortInfo.setStopBit(new Integer(decoderCfg.stopBit));
		serialPortInfo.setDecoderAddress(new Integer(
		// decoderAddress
				decoderCfg.decoderAddress));
		serialPortInfo.setDecoderType(new Integer(decoderCfg.decoderType));

		return serialPortInfo;
	}

	public boolean setDecoderCfg(SerialPortInfo serialPortInfo) {
		// int channel = serialPortInfo.getDecoderAddress().intValue();
		int channel = serialPortInfo.getVideoId().intValue();
		DecoderCfg decoderCfg = new DecoderCfg();
		if (!HcNetAdapter.getDecoderCfg(userId, channel, decoderCfg)) {
			return false;
		}
		// hik SDK changed baudrate

		// decoderCfg.baudRate =
		// getHcBaudRate(serialPortInfo.getBaudRate().intValue());
		decoderCfg.baudRate = serialPortInfo.getBaudRate().intValue();
		// hik SDK changed
		// decoderCfg.dataBit = serialPortInfo.getDataBit().intValue() - 5;
		decoderCfg.dataBit = serialPortInfo.getDataBit().intValue();
		if (null != serialPortInfo.getFlowcontrol()) {
			decoderCfg.flowControl = serialPortInfo.getFlowcontrol().intValue();
		}
		decoderCfg.parity = serialPortInfo.getParity().intValue();
		// hik SDK changed
		// decoderCfg.stopBit = serialPortInfo.getStopBit().intValue() - 1;
		decoderCfg.stopBit = serialPortInfo.getStopBit().intValue();
		if (null != serialPortInfo.getDecoderAddress()) {
			decoderCfg.decoderAddress = serialPortInfo.getDecoderAddress()
					.intValue();
		}
		if (null != serialPortInfo.getDecoderType()) {
			decoderCfg.decoderType = serialPortInfo.getDecoderType().intValue();
		}
		return HcNetAdapter.setDecoderCfg(userId, channel, decoderCfg);
	}

	public CruiseTrackInfo[] getCruiseTrackInfo(Integer ptzId,
			Integer cruiseNumber) {
		int MAX_CRUISECOUNT = 8;

		ArrayList cruiseTrackList = new ArrayList();

		if (null != cruiseNumber) {
			CruiseTrackInfo oneCruiseTrackInfo = getOneCruiseTrackInfo(ptzId,
					cruiseNumber);
			cruiseTrackList.add(oneCruiseTrackInfo);
		} else {

			CruiseCountCfg cruiseCountCfg = new CruiseCountCfg();
			if (!HcNetAdapter.getCrusieCountCfg(userId, ptzId.intValue(),
					cruiseCountCfg)) {
			}

			for (int i = 0; i < MAX_CRUISECOUNT; i++) {
				int criterion = (int) Math.pow(2, i);
				boolean hasSet = ((cruiseCountCfg.dwCruiseStatus & criterion) != 0);
				if (hasSet) {
					CruiseTrackInfo oneCruiseTrackInfo = getOneCruiseTrackInfo(
							ptzId, new Integer(i + 1));
					cruiseTrackList.add(oneCruiseTrackInfo);
				}
			}
		}

		return (CruiseTrackInfo[]) cruiseTrackList
				.toArray(new CruiseTrackInfo[0]);
	}

	/*
	 * 
	 * @param cruiseNumber
	 */
	private CruiseTrackInfo getOneCruiseTrackInfo(Integer ptzId,
			Integer cruiseNumber) {
		CruiseCfg cruiseCfg = new CruiseCfg();
		if (!HcNetAdapter.getCruiseConfig(userId, ptzId.intValue(),
				cruiseNumber.intValue(), cruiseCfg)) {
		}
		CruiseTrackInfo cruiseTrackInfo = new CruiseTrackInfo();
		cruiseTrackInfo.setPtzId(ptzId);
		cruiseTrackInfo.setCruiseNumber(cruiseNumber);
		ArrayList cruisePointList = new ArrayList();
		for (int i = 0; i < cruiseCfg.dwListCount; i++) {
			if (null != cruiseCfg.struCruisePoint[i]) {
				CruisePointInfo cruisePointInfo = new CruisePointInfo();
				cruisePointInfo.setPresetIndex(new Integer(
						cruiseCfg.struCruisePoint[i].byPresetNo & 0xff));
				cruisePointInfo.setSpeed((new Integer(
						cruiseCfg.struCruisePoint[i].bySpeed & 0xff)));
				cruisePointInfo.setDwellTime((new Integer(
						cruiseCfg.struCruisePoint[i].byDwellTime & 0xff)));
				cruisePointList.add(cruisePointInfo);
			}
		}
		CruisePointInfo[] cruisePoints = (CruisePointInfo[]) cruisePointList
				.toArray(new CruisePointInfo[0]);
		cruiseTrackInfo.setCruisePoints(cruisePoints);
		return cruiseTrackInfo;
	}

	public boolean setCruiseTrackInfo(CruiseTrackInfo cruiseTrackInfo) {
		int MAX_CRUISEPONITCOUNT = 16;
		CruiseCfg cruiseCfg = new CruiseCfg();
		int channel = cruiseTrackInfo.getPtzId().intValue();
		int cruiseNo = cruiseTrackInfo.getCruiseNumber().intValue();

		CruisePointInfo[] cruisePoints = cruiseTrackInfo.getCruisePoints();

		cruiseCfg.dwListCount = cruisePoints.length;
		if (cruiseCfg.dwListCount > MAX_CRUISEPONITCOUNT) {
			cruiseCfg.dwListCount = MAX_CRUISEPONITCOUNT;
		}
		cruiseCfg.struCruisePoint = new CruisePoint[MAX_CRUISEPONITCOUNT];
		for (int i = 0; i < cruiseCfg.dwListCount; i++) {
			CruisePoint tempCruisePoint = new CruisePoint();
			tempCruisePoint.byPresetNo = cruisePoints[i].getPresetIndex()
					.byteValue();
			tempCruisePoint.bySpeed = cruisePoints[i].getSpeed().byteValue();
			tempCruisePoint.byDwellTime = cruisePoints[i].getDwellTime()
					.byteValue();
			cruiseCfg.struCruisePoint[i] = tempCruisePoint;
		}

		return HcNetAdapter.setCruiseConfig(userId, channel, cruiseNo,
				cruiseCfg);
	}

	public boolean transparentChannel(
			TransparentChannelInfo transparentChannelInfo) {
		SerialMessageInfo serialMessageInfo = new SerialMessageInfo();
		serialMessageInfo.userIdentity = 0;
		serialMessageInfo.serialPort = Integer.valueOf(
				transparentChannelInfo.getComNumber()).intValue();
		if (SerialMessageInfo.SERIALPORT_232 != serialMessageInfo.serialPort) {
			System.out.println("Error:The ComNumber is "
					+ serialMessageInfo.serialPort);
		}
		serialMessageInfo.channel = 0;
		try {
			serialMessageInfo.dataToSend = transparentChannelInfo.getData()
					.getBytes(HikVisionDVRClient.CHARSET);
		} catch (UnsupportedEncodingException e) {
			System.out.println("Error:transparentChannelInfo.getData().getBytes(\""
					+ HikVisionDVRClient.CHARSET + "\"); data= "
					+ transparentChannelInfo.getData());
		}

		return HcNetAdapter.sendSerialMessage(userId, serialMessageInfo);
	}

	public LocalStorageTask getVsLocalStorageTask(int videoId) {
		RecordCfg recordCfg = new RecordCfg();
		if (!HcNetAdapter.getRecordCfg(userId, videoId, recordCfg)) {
			System.out.println("HcNetAdapter.getRecordCfg failed...");
		}

		LocalStorageTask storageTask = new LocalStorageTask();
		storageTask.setVideoId(new Integer(videoId));
		storageTask.setRecordEnable(new Integer(recordCfg.recordEnable));
		storageTask.setRecordTime(new Integer(recordCfg.recordTime));
		storageTask.setPreRecordTime(new Integer(recordCfg.preRecordTime));
		ArrayList schedList = new ArrayList();
		int MAX_DAYS = recordCfg.recordSched.length;
		for (int i = 0; i < MAX_DAYS; i++) {
			int MAX_TIMESEGMENT = recordCfg.recordSched[i].length;
			for (int j = 0; j < MAX_TIMESEGMENT; j++) {
				RecordSchedule recSchedule = new RecordSchedule();
				recSchedule
						.setRecordType(recordCfg.recordSched[i][j].recordType);
				recSchedule.setWeekday(i + 1);
				recSchedule.setStartHour(recordCfg.recordSched[i][j].startHour);
				recSchedule.setStartMin(recordCfg.recordSched[i][j].startMin);
				recSchedule.setStopHour(recordCfg.recordSched[i][j].stopHour);
				recSchedule.setStopMin(recordCfg.recordSched[i][j].stopMin);
				schedList.add(recSchedule);
			}
		}
		storageTask.setSchedule((RecordSchedule[]) schedList
				.toArray(new RecordSchedule[0]));

		DeviceCfg deviceCfg = new DeviceCfg();
		if (!HcNetAdapter.getDeviceCfg(userId, 0, deviceCfg)) {
		}
		storageTask.setRecycleRecEnable(new Integer(deviceCfg.recycleRecord));

		return storageTask;
	}

	public DiskSizeInfo[] queryVsLocalDisk() {
		WorkState workState = new WorkState();
		if (!HcNetAdapter.getWorkState(userId, workState)) {
		}

		ArrayList diskList = new ArrayList();
		int MAX_DISKNUM = workState.disk.length;
		for (int i = 0; i < MAX_DISKNUM; i++) {
			DiskSizeInfo sizeInfo = new DiskSizeInfo();
			sizeInfo.setDiskId(new Integer(i + 1));
			sizeInfo.setTotalSize(new Long(workState.disk[i].totalSize));
			sizeInfo.setFreeSize(new Long(workState.disk[i].freeSize));
			diskList.add(sizeInfo);
		}
		return (DiskSizeInfo[]) diskList.toArray(new DiskSizeInfo[0]);
	}

	public RecordFile[] queryVsLocalStorageFiles(StorageQuery query) {
		ArrayList list = new ArrayList();
		getStorageFiles(query, list);

		List fileList = new ArrayList();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			LocalStorageFile f = (LocalStorageFile) it.next();
			RecordFile file = new RecordFile();
			file.setFilename(f.filename);
			file.setStartTime(f.getStartTime());
			file.setStopTime(f.getStopTime());
			file.setSize(String.valueOf(f.fileSize));
			fileList.add(file);
		}
		return (RecordFile[]) fileList.toArray(new RecordFile[0]);
	}

	private void getStorageFiles(StorageQuery query, List list) {
		switch (query.getFileType().intValue()) {
		case 0:
		case 1:
		case 2:
		case 3:
			getRecordStorageFiles(query, list);
			break;
		case 4:
		case 5:
		case 6:
			getCapturePictureStorageFiles(query, list);
			break;
		default:
		}
	}

	private void getCapturePictureStorageFiles(StorageQuery query, List list) {
		TimeCfg startTime = new TimeCfg();
		startTime.year = query.getFromYear().intValue();
		startTime.month = query.getFromMonth().intValue();
		startTime.date = query.getFromDay().intValue();
		startTime.hour = query.getFromHour().intValue();

		TimeCfg stopTime = new TimeCfg();
		stopTime.year = query.getToYear().intValue();
		stopTime.month = query.getToMonth().intValue();
		stopTime.date = query.getToDay().intValue();
		stopTime.hour = query.getToHour().intValue();

		boolean needCardNum = false;
		String cardNumber = "0";
		// int fileType=query.getFileType().intValue();
		int fileType = 0;
		try {
			if (!HcNetAdapter.getCapturePictureStorageFiles(userId, query
					.getVideoId().intValue(), fileType, needCardNum, cardNumber
					.getBytes(HikVisionDVRClient.CHARSET), startTime, stopTime,
					list)) {
			}
		} catch (UnsupportedEncodingException e) {
			System.out.println("cardNumber.getBytes(\"" + HikVisionDVRClient.CHARSET
					+ "\") encode error!" + e);
		}
	}

	private void getRecordStorageFiles(StorageQuery query, List list) {
		TimeCfg startTime = new TimeCfg();
		startTime.year = query.getFromYear().intValue();
		startTime.month = query.getFromMonth().intValue();
		startTime.date = query.getFromDay().intValue();
		startTime.hour = query.getFromHour().intValue();

		TimeCfg stopTime = new TimeCfg();
		stopTime.year = query.getToYear().intValue();
		stopTime.month = query.getToMonth().intValue();
		stopTime.date = query.getToDay().intValue();
		stopTime.hour = query.getToHour().intValue();

		int fileType = query.getFileType().intValue();
		if (3 == fileType) {
			fileType = 0xff;
		}

		if (!HcNetAdapter.getStorageFiles(userId,
				query.getVideoId().intValue(), startTime, stopTime, fileType,
				list)) {
		}
	}

	public boolean setVsLocalStorageTask(LocalStorageTask storageTask) {

		int channel = storageTask.getVideoId().intValue();
		RecordCfg recordCfg = new RecordCfg();
		if (!HcNetAdapter.getRecordCfg(userId, channel, recordCfg)) {
			return false;
		}

		// Stop All Day alarm Record on this channel
		for (int i = 0; i < recordCfg.recordAllDay.length; i++) {
			recordCfg.recordAllDay[i].recordAllDayEnable = 0;
		}

		// recordCfg.preRecordTime = storageTask.getPreRecordTime().intValue();
		recordCfg.recordEnable = storageTask.getRecordEnable().intValue();
		ArrayList[] list = { new ArrayList(), new ArrayList(), new ArrayList(),
				new ArrayList(), new ArrayList(), new ArrayList(),
				new ArrayList() };
		RecordSchedule[] schedule = storageTask.getSchedule();
		for (int i = 0; i < schedule.length; i++) {
			RecordSched recordSched = new RecordSched();
			recordSched.recordType = (byte) schedule[i].getRecordType();
			recordSched.startHour = (byte) schedule[i].getStartHour();
			recordSched.startMin = (byte) schedule[i].getStartMin();
			recordSched.stopHour = (byte) schedule[i].getStopHour();
			recordSched.stopMin = (byte) schedule[i].getStopMin();
			list[schedule[i].getWeekday() - 1].add(recordSched);
		}
		RecordSched emptySchedule = new RecordSched();
		int MAX_DAYS = recordCfg.recordSched.length;
		for (int i = 0; i < MAX_DAYS; i++) {
			int MAX_TIMESEGMENT = recordCfg.recordSched[i].length;
			int SCHED_NUM = list[i].size();
			for (int j = 0; j < MAX_TIMESEGMENT; j++) {
				if (j < SCHED_NUM) {
					recordCfg.recordSched[i][j] = (RecordSched) list[i].get(j);
				} else {
					recordCfg.recordSched[i][j] = emptySchedule;
				}
			}
		}
		DeviceCfg deviceCfg = new DeviceCfg();
		if (!HcNetAdapter.getDeviceCfg(userId, 0, deviceCfg)) {
			return false;
		}
		deviceCfg.recycleRecord = storageTask.getRecycleRecEnable().intValue() == 0 ? 0
				: 1;

		return HcNetAdapter.setRecordCfg(userId, channel, recordCfg)
				& HcNetAdapter.setDeviceCfg(userId, 0, deviceCfg);
	}

	public boolean stopVsLocalStorageTask(int videoId, boolean isStop) {
		RecordCfg recordCfg = new RecordCfg();
		if (!HcNetAdapter.getRecordCfg(userId, videoId, recordCfg)) {
			return false;
		}
		recordCfg.recordEnable = isStop ? 0 : 1;
		return HcNetAdapter.setRecordCfg(userId, videoId, recordCfg);
	}

	public boolean setVsAlarmConfiguration(AlarmConfiguration alarmCfg) {
		alarmCfg = this.validateAlarmConfiguration(alarmCfg);
		// -----------Config The HB Server--------------------------//
		ManageCfg manageCfg = new ManageCfg();
		if (!HcNetAdapter.getManageCfg(userId, manageCfg)) {
			return false;
		}
		manageCfg.heartBeatEnable = alarmCfg.connectionDetectionEnabled;
		if (!HcNetAdapter.setManageCfg(userId, manageCfg))
			return false;

		// -----------STOP ALL ALARM------------------//
		for (int i = 0; i < deviceInfo.alarmInPortNum; i++) {
			AlarmInCfg alarmInCfg = new AlarmInCfg();
			if (!HcNetAdapter.getAlarmInCfg(userId, i, alarmInCfg)) {
				System.out.println("SetVsAlarmConfiguration getAlarmCfg fail");
				return false;
			}
			alarmInCfg.alarmInHandle = 0;
			if (!HcNetAdapter.setAlarmInCfg(userId, i, alarmInCfg)) {
				System.out.println("SetVsAlarmConfiguration setAlarmCfg fail");
				return false;
			}
		}
		for (int i = 1; i <= deviceInfo.channelNum; i++) {
			PicCfg picCfg = new PicCfg();
			if (!HcNetAdapter.getPicCfg(userId, i, picCfg)) {
				System.out.println("SetVsAlarmConfiguration getPicCfg fail");
				return false;
			}
			picCfg.videoLoseAlarmEnabled = 0;
			picCfg.hideAlarmEnable = 0;
			picCfg.motionAlarmEnable = 0;
			if (!HcNetAdapter.setPicCfg(userId, i, picCfg)) {
				System.out.println("SetVsAlarmConfiguration setPicCfg fail");
				return false;
			}
		}
		// ------------------Initial All Record Channel-----------------//
		// Get the Channels Number that alarm record on;
		HashSet recordChannelSet = new HashSet();
		for (int i = 0; alarmCfg.gpinAlarm != null
				&& i < alarmCfg.gpinAlarm.length; i++) {
			for (int j = 0; alarmCfg.gpinAlarm[i].gpinAlarmRecord != null
					&& j < alarmCfg.gpinAlarm[i].gpinAlarmRecord.length; j++) {
				recordChannelSet.add(new Integer(
						alarmCfg.gpinAlarm[i].gpinAlarmRecord[j]));
			}
		}
		for (int i = 0; alarmCfg.videoAlarm != null
				&& i < alarmCfg.videoAlarm.length; i++) {
			for (int j = 0; alarmCfg.videoAlarm[i].motionDetectionAlarmRecord != null
					&& j < alarmCfg.videoAlarm[i].motionDetectionAlarmRecord.length; j++) {
				recordChannelSet.add(new Integer(
						alarmCfg.videoAlarm[i].motionDetectionAlarmRecord[j]));
			}
		}
		Iterator iterator = recordChannelSet.iterator();
		while (iterator.hasNext()) {
			int channelNumber = ((Integer) iterator.next()).intValue();
			RecordCfg recordCfg = new RecordCfg();
			if (!HcNetAdapter.getRecordCfg(userId, channelNumber, recordCfg)) {
				System.out.println("SetVsAlarmConfiguration getRecordCfg fail");
				return false;
			}
			recordCfg.recordEnable = 1;
			recordCfg.recordTime = alarmCfg.alarmRecordTime;
			recordCfg.preRecordTime = alarmCfg.alarmPreRecordTime;
			// ----------7x24 Hours Alarm | Motion Record-----------//
			RecordAllDay recordAllDay = new RecordAllDay();
			recordAllDay.recordAllDayEnable = 1;
			// type 3 means motion detect and alarm record
			recordAllDay.recordType = 3;
			for (int i = 0; i < recordCfg.recordAllDay.length; i++) {
				recordCfg.recordAllDay[i] = recordAllDay;
			}
			if (!HcNetAdapter.setRecordCfg(userId, channelNumber, recordCfg)) {
				System.out.println("SetVsAlarmConfiguration setRecordCfg fail");
				return false;
			}
		}

		// ------------------Initial All alarmout channel ----------------//
		// 7 x 24 Hours alarm out
		SchedTime allDay = new SchedTime();
		allDay.startHour = 0;
		allDay.startMin = 0;
		allDay.stopHour = 24;
		allDay.stopMin = 0;
		for (int i = 0; i < deviceInfo.alarmOutPortNum; i++) {
			AlarmOutCfg alarmOutCfg = new AlarmOutCfg();
			if (!HcNetAdapter.getAlarmOutCfg(userId, i, alarmOutCfg)) {
				System.out.println("SetVsAlarmConfiguration getAlarmOutCfg fail");
				return false;
			}
			// change

			alarmOutCfg.delay = alarmCfg.alarmOutputTime;
			// alarmOutCfg.delay = -1;
			for (int j = 0; j < alarmOutCfg.alarmTime.length; j++) {
				alarmOutCfg.alarmTime[j][0] = allDay;
			}
			if (!HcNetAdapter.setAlarmOutCfg(userId, i, alarmOutCfg)) {
				System.out.println("SetVsAlarmConfiguration setAlarmOutCfg fail");
				return false;
			}
		}
		// ------------------System Exception -----------------------//
		ExceptionCfg exceptionCfg = new ExceptionCfg();
		// exceptionCfg.netDisconnectEnable =
		// alarmCfg.connectionDetectionEnabled;
		exceptionCfg.diskErrorEnable = alarmCfg.diskErrorAlarmEnabled;
		exceptionCfg.diskFullEnable = alarmCfg.diskFullAlarmEnabled;
		if (!HcNetAdapter.setExceptionCfg(userId, 0, exceptionCfg)) {
			System.out.println("SetVsAlarmConfiguration setExceptionCfg fail");
			return false;
		}
		JPEGCFG jpegCfg = new JPEGCFG();
		if (!HcNetAdapter.getJPEGCFG(userId, jpegCfg)) {
			System.out.println("SetVsAlarmConfiguration getJPEGCfg fail");
			// modified by vondart to accomodate dvs without alarm shoot
			// return false;
		}
		JPEGPARA jpegPara = new JPEGPARA();
		switch (alarmCfg.photoResolution) {
		case 0:
			jpegPara.wPicSize = 1;
			break;
		case 1:
			jpegPara.wPicSize = 0;
			break;
		default:
			jpegPara.wPicSize = alarmCfg.photoResolution;
		}
		jpegPara.wPicQuality = alarmCfg.photoQuality;
		jpegCfg.struJpegPara = new JPEGPARA[deviceInfo.channelNum];
		Arrays.fill(jpegCfg.struJpegPara, jpegPara);
		jpegCfg.dwTriggerPicTimes = new int[deviceInfo.channelNum];
		Arrays.fill(jpegCfg.dwTriggerPicTimes, alarmCfg.shootTimes);

		jpegCfg.dwAlarmInPicChanTriggered = new int[deviceInfo.alarmInPortNum];
		Arrays.fill(jpegCfg.dwAlarmInPicChanTriggered, 0);

		for (int i = 0; alarmCfg.gpinAlarm != null
				&& i < alarmCfg.gpinAlarm.length; i++) {
			AlarmConfiguration.GPINAlarm gpinAlarm = alarmCfg.gpinAlarm[i];
			AlarmInCfg alarmInCfg = new AlarmInCfg();
			if (!HcNetAdapter.getAlarmInCfg(userId,
					gpinAlarm.channelNumber - 1, alarmInCfg)) {
				return false;
			}
			alarmInCfg.alarmHandleType = 0x04 | 0x08;

			alarmInCfg.alarmInHandle = gpinAlarm.gpinAlarmEnable ? 1 : 0;
			alarmInCfg.state = gpinAlarm.gpinAlarmStatus;
			Arrays.fill(alarmInCfg.alarmOut, (byte) 0); // Reset alarm out
														// channel;
			for (int j = 0; gpinAlarm.gpinAlarmOutput != null
					&& j < gpinAlarm.gpinAlarmOutput.length; j++) {
				alarmInCfg.alarmOut[gpinAlarm.gpinAlarmOutput[j].channelNumber - 1] = 1;
			}
			Arrays.fill(alarmInCfg.alarmRecordChannel, (byte) 0); // Reset
																	// record
																	// channel
			for (int j = 0; gpinAlarm.gpinAlarmRecord != null
					&& j < gpinAlarm.gpinAlarmRecord.length; j++) {
				alarmInCfg.alarmRecordChannel[gpinAlarm.gpinAlarmRecord[j] - 1] = 1;
			}

			for (int j = 0; j < alarmInCfg.alarmTime.length; j++) {
				alarmInCfg.alarmTime[j][0] = allDay;
			}

			if (gpinAlarm.gpinAlarmShoot.length > 0) {
				alarmInCfg.alarmHandleType |= 0x20;
				jpegCfg.wBurstMode |= 0x1;
				int captureChannels = getCaptureChannels(gpinAlarm.gpinAlarmShoot);
				jpegCfg.dwAlarmInPicChanTriggered[gpinAlarm.channelNumber - 1] = captureChannels;
			}

			if (!HcNetAdapter.setAlarmInCfg(userId,
					gpinAlarm.channelNumber - 1, alarmInCfg)) {
				System.out.println("SetVsAlarmConfiguration setAlarmInCfg fail");
				return false;
			}
		}
		// -----------------------VIDEO ALARM-------------------------/
		for (int i = 0; alarmCfg.videoAlarm != null
				&& i < alarmCfg.videoAlarm.length; i++) {
			AlarmConfiguration.VideoAlarm videoAlarm = alarmCfg.videoAlarm[i];
			PicCfg picCfg = new PicCfg();
			if (!HcNetAdapter.getPicCfg(userId, videoAlarm.videoId, picCfg)) {
				System.out.println("SetVsAlarmConfiguration getPicCfg fail");
				return false;
			}

			// ----------------VIDEO LOST ALARM ---------------/
			if (videoAlarm.videoLoseAlarmEnabled) {
				picCfg.videoLoseAlarmEnabled = 1;
				picCfg.videoLoseHandleType = 0x04 | 0x08;

				Arrays.fill(picCfg.videoLoseAlarmOut, (byte) 0);
				for (int j = 0; videoAlarm.videoLoseAlarmOutput != null
						&& j < videoAlarm.videoLoseAlarmOutput.length; j++) {
					picCfg.videoLoseAlarmOut[videoAlarm.videoLoseAlarmOutput[j].channelNumber - 1] = 1;
				}
				//
				for (int j = 0; j < picCfg.videoLoseAlarmTime.length; j++) {
					picCfg.videoLoseAlarmTime[j][0] = allDay;
				}
			}
			// --------------MOTION DETECTION ---------------/
			if (videoAlarm.motionDetectionAlarmEnabled) {
				picCfg.motionAlarmEnable = 1;
				picCfg.montionSenstive = videoAlarm.motionDetectionSensitivity;
				picCfg.motionHandleType = 0x04 | 0x08;

				byte[] mdBlocks = videoAlarm.motionDetectionBlocks;
				for (int j = 0; j < picCfg.motionScope.length; j++) {
					for (int k = 0; k < picCfg.motionScope[j].length; k++) {
						int index = picCfg.motionScope[j].length * j + k;
						if (index < mdBlocks.length) {
							picCfg.motionScope[j][k] = mdBlocks[index];
						} else {
							picCfg.motionScope[j][k] = 0;
						}
					}
				}
				Arrays.fill(picCfg.motionAlarmOut, (byte) 0);
				for (int j = 0; videoAlarm.motionDetectionAlarmOutput != null
						&& j < videoAlarm.motionDetectionAlarmOutput.length; j++) {
					picCfg.motionAlarmOut[videoAlarm.motionDetectionAlarmOutput[j].channelNumber - 1] = 1;
				}
				Arrays.fill(picCfg.motionRecordChannel, (byte) 0);
				for (int j = 0; videoAlarm.motionDetectionAlarmRecord != null
						&& j < videoAlarm.motionDetectionAlarmRecord.length; j++) {
					picCfg.motionRecordChannel[videoAlarm.motionDetectionAlarmRecord[j] - 1] = 1;
				}
				//
				for (int j = 0; j < picCfg.motionAlarmTime.length; j++) {
					picCfg.motionAlarmTime[j][0].startHour = videoAlarm.motionDetectionAlarmTime
							.getStartHour();
					picCfg.motionAlarmTime[j][0].startMin = videoAlarm.motionDetectionAlarmTime
							.getStartMin();
					picCfg.motionAlarmTime[j][0].stopHour = videoAlarm.motionDetectionAlarmTime
							.getStopHour();
					picCfg.motionAlarmTime[j][0].stopMin = videoAlarm.motionDetectionAlarmTime
							.getStopMin();
				}

				if (videoAlarm.motionDetectionAlarmShoot.length > 0) {
					picCfg.motionHandleType |= 0x20;
					jpegCfg.wBurstMode |= 0x2;
				}

			}
			// --------------HIDE DETECTION-----------------/
			if (videoAlarm.hideDetectionAlarmEnabled) {
				picCfg.hideAlarmEnable = 1;
				picCfg.hideAlarmAreaHeight = videoAlarm.hideDetectionHeight;
				picCfg.hideAlarmAreaTopLeftX = videoAlarm.hideDetectionX;
				picCfg.hideAlarmAreaTopLeftY = videoAlarm.hideDetectionY;
				picCfg.hideAlarmAreaWidth = videoAlarm.hideDetectionWidth;
				picCfg.hideAlarmHandleType = 0x04 | 0x08;

				Arrays.fill(picCfg.hideAlarmOut, (byte) 0);
				for (int j = 0; videoAlarm.hideDetectionAlarmOutput != null
						&& j < videoAlarm.hideDetectionAlarmOutput.length; j++) {
					picCfg.hideAlarmOut[videoAlarm.hideDetectionAlarmOutput[j].channelNumber - 1] = 1;
				}
				//
				for (int j = 0; j < picCfg.hideAlarmTime.length; j++) {
					picCfg.hideAlarmTime[j][0].startHour = videoAlarm.hideDetectionAlarmTime
							.getStartHour();
					picCfg.hideAlarmTime[j][0].startMin = videoAlarm.hideDetectionAlarmTime
							.getStartMin();
					picCfg.hideAlarmTime[j][0].stopHour = videoAlarm.hideDetectionAlarmTime
							.getStopHour();
					picCfg.hideAlarmTime[j][0].stopMin = videoAlarm.hideDetectionAlarmTime
							.getStopMin();
				}
			}
			if (!HcNetAdapter.setPicCfg(userId, videoAlarm.videoId, picCfg)) {
				System.out.println("SetVsAlarmConfiguration setPicCfg fail");
				return false;
			}
		}

		if (!HcNetAdapter.setJPEGCFG(userId, jpegCfg)) {
			System.out.println("SetVsAlarmConfiguration setJPEGCfg fail");
			// modified by vondart to accomodate dvs without alarm shoot
			return false;
		}
		// image format
		// temporarily commented
		ImageFormat imageFormat = new ImageFormat();
		imageFormat.imageFormate = alarmCfg.imageFormat.getBytes();
		if (!HcNetAdapter.setImageFormat(userId, 0, imageFormat)) {
			System.out.println("SetVsAlarmConfiguration setImageFormat fail");
			return false;
		}
		return true;
	}

	private int getCaptureChannels(int[] gpinAlarmShoot) {
		int returnIntValue = 0;
		for (int i = 0; i < gpinAlarmShoot.length; i++) {
			int powedIntVale = (int) Math.pow(2, gpinAlarmShoot[i]);
			returnIntValue |= powedIntVale;
		}
		return returnIntValue;
	}

	private AlarmConfiguration validateAlarmConfiguration(
			AlarmConfiguration alarmCfg) {
		int MAX_CHANNEL_IN = deviceInfo.alarmInPortNum;
		int MAX_CHANNEL_OUT = deviceInfo.alarmOutPortNum;
		int MAX_CHANNEL_VIDEO = deviceInfo.channelNum;
		// ---------------GPIN-----------------------------------//
		ArrayList gpinAlarmList = new ArrayList();
		for (int i = 0; i < alarmCfg.gpinAlarm.length; i++) {
			if (alarmCfg.gpinAlarm[i].channelNumber < 1
					|| alarmCfg.gpinAlarm[i].channelNumber > MAX_CHANNEL_IN) {
				System.out.println("IGNORE GPIN CHANNEL[1-" + MAX_CHANNEL_IN + "]: "
						+ alarmCfg.gpinAlarm[i].channelNumber);
				continue;
			}
			gpinAlarmList.add(alarmCfg.gpinAlarm[i]);
			// -------------------------ALARM OUT------------------------//
			ArrayList gpinAlarmOutList = new ArrayList();
			for (int j = 0; j < alarmCfg.gpinAlarm[i].gpinAlarmOutput.length; j++) {
				if (alarmCfg.gpinAlarm[i].gpinAlarmOutput[j].channelNumber < 1
						|| alarmCfg.gpinAlarm[i].gpinAlarmOutput[j].channelNumber > MAX_CHANNEL_OUT) {
					System.out.println("IGNORE ALARM OUT CHANNEL[1-"
							+ MAX_CHANNEL_OUT
							+ "]: "
							+ alarmCfg.gpinAlarm[i].gpinAlarmOutput[j].channelNumber
							+ " ON GPIN CHANNEL "
							+ alarmCfg.gpinAlarm[i].channelNumber);
					continue;
				}
				gpinAlarmOutList.add(alarmCfg.gpinAlarm[i].gpinAlarmOutput[j]);
			}
			alarmCfg.gpinAlarm[i].gpinAlarmOutput = (AlarmConfiguration.AlarmOutput[]) gpinAlarmOutList
					.toArray(new AlarmConfiguration.AlarmOutput[0]);
			// ------------------------ALARM RECORD
			// CHANNEL--------------------//
			ArrayList gpinAlarmRecordList = new ArrayList();
			for (int j = 0; j < alarmCfg.gpinAlarm[i].gpinAlarmRecord.length; j++) {
				if (alarmCfg.gpinAlarm[i].gpinAlarmRecord[j] < 1
						|| alarmCfg.gpinAlarm[i].gpinAlarmRecord[j] > MAX_CHANNEL_VIDEO) {
					System.out.println("IGNORE ALARM RECORD CHANNEL[1-"
							+ MAX_CHANNEL_VIDEO + "]: "
							+ alarmCfg.gpinAlarm[i].gpinAlarmRecord[j]
							+ " ON GPIN CHANNEL "
							+ alarmCfg.gpinAlarm[i].channelNumber);
					continue;
				}
				gpinAlarmRecordList.add(new Integer(
						alarmCfg.gpinAlarm[i].gpinAlarmRecord[j]));
			}
			alarmCfg.gpinAlarm[i].gpinAlarmRecord = toIntArray(gpinAlarmRecordList);

			ArrayList gpinAlarmShootList = new ArrayList();
			for (int j = 0; j < alarmCfg.gpinAlarm[i].gpinAlarmShoot.length; j++) {
				if (alarmCfg.gpinAlarm[i].gpinAlarmShoot[j] < 1
						|| alarmCfg.gpinAlarm[i].gpinAlarmShoot[j] > MAX_CHANNEL_VIDEO) {
					System.out.println("IGNORE ALARM Shoot CHANNEL[1-"
							+ MAX_CHANNEL_VIDEO + "]: "
							+ alarmCfg.gpinAlarm[i].gpinAlarmShoot[j]
							+ " ON GPIN CHANNEL "
							+ alarmCfg.gpinAlarm[i].channelNumber);
					continue;
				}
				gpinAlarmShootList.add(new Integer(
						alarmCfg.gpinAlarm[i].gpinAlarmShoot[j]));
			}
			alarmCfg.gpinAlarm[i].gpinAlarmShoot = toIntArray(gpinAlarmShootList);

		}
		alarmCfg.gpinAlarm = (AlarmConfiguration.GPINAlarm[]) gpinAlarmList
				.toArray(new AlarmConfiguration.GPINAlarm[0]);
		// ------------------VIDEO
		// ALARM---------------------------------------//
		ArrayList videoAlarmList = new ArrayList();
		for (int i = 0; i < alarmCfg.videoAlarm.length; i++) {
			if (alarmCfg.videoAlarm[i].videoId < 1
					|| alarmCfg.videoAlarm[i].videoId > deviceInfo.channelNum) {
				System.out.println("IGNORE VIDEO ALARM CHANNEL[1-" + MAX_CHANNEL_VIDEO
						+ "]: " + alarmCfg.videoAlarm[i].videoId);
				continue;
			}
			videoAlarmList.add(alarmCfg.videoAlarm[i]);
			// -------------VIDEO LOST-------------------------//
			ArrayList videoLoseAlarmOutputList = new ArrayList();
			for (int j = 0; j < alarmCfg.videoAlarm[i].videoLoseAlarmOutput.length; j++) {
				if (alarmCfg.videoAlarm[i].videoLoseAlarmOutput[j].channelNumber < 1
						|| alarmCfg.videoAlarm[i].videoLoseAlarmOutput[j].channelNumber > MAX_CHANNEL_OUT) {
					System.out.println("IGNORE VIDEO LOST ALARM OUT CHANNEL[1-"
							+ MAX_CHANNEL_OUT
							+ "]: "
							+ alarmCfg.videoAlarm[i].videoLoseAlarmOutput[j].channelNumber
							+ " ON VIDEO CHANNEL "
							+ alarmCfg.videoAlarm[i].videoId);
					continue;
				}
				videoLoseAlarmOutputList
						.add(alarmCfg.videoAlarm[i].videoLoseAlarmOutput[j]);
			}
			alarmCfg.videoAlarm[i].videoLoseAlarmOutput = (AlarmConfiguration.AlarmOutput[]) videoLoseAlarmOutputList
					.toArray(new AlarmConfiguration.AlarmOutput[0]);
			// -------------HIDEN DETECT-----------------------//
			ArrayList hideDetectionAlarmOutputList = new ArrayList();
			for (int j = 0; j < alarmCfg.videoAlarm[i].hideDetectionAlarmOutput.length; j++) {
				if (alarmCfg.videoAlarm[i].hideDetectionAlarmOutput[j].channelNumber < 1
						|| alarmCfg.videoAlarm[i].hideDetectionAlarmOutput[j].channelNumber > MAX_CHANNEL_OUT) {
					System.out.println("IGNORE HIDEN ALARM OUT CHANNEL[1-"
							+ MAX_CHANNEL_OUT
							+ "]: "
							+ alarmCfg.videoAlarm[i].hideDetectionAlarmOutput[j].channelNumber
							+ " ON VIDEO CHANNEL "
							+ alarmCfg.videoAlarm[i].videoId);
					continue;
				}
				hideDetectionAlarmOutputList
						.add(alarmCfg.videoAlarm[i].hideDetectionAlarmOutput[j]);
			}
			alarmCfg.videoAlarm[i].hideDetectionAlarmOutput = (AlarmConfiguration.AlarmOutput[]) hideDetectionAlarmOutputList
					.toArray(new AlarmConfiguration.AlarmOutput[0]);
			// -------------MOTION DETECT----------------------//
			ArrayList motionDetectionAlarmOutputList = new ArrayList();
			for (int j = 0; j < alarmCfg.videoAlarm[i].motionDetectionAlarmOutput.length; j++) {
				if (alarmCfg.videoAlarm[i].motionDetectionAlarmOutput[j].channelNumber < 1
						|| alarmCfg.videoAlarm[i].motionDetectionAlarmOutput[j].channelNumber > MAX_CHANNEL_OUT) {
					System.out.println("IGNORE MOTION ALARM OUT CHANNEL[1-"
							+ MAX_CHANNEL_OUT
							+ "]: "
							+ alarmCfg.videoAlarm[i].motionDetectionAlarmOutput[j].channelNumber
							+ " ON VIDEO CHANNEL "
							+ alarmCfg.videoAlarm[i].videoId);
					continue;
				}
				motionDetectionAlarmOutputList
						.add(alarmCfg.videoAlarm[i].motionDetectionAlarmOutput[j]);
			}
			alarmCfg.videoAlarm[i].motionDetectionAlarmOutput = (AlarmConfiguration.AlarmOutput[]) motionDetectionAlarmOutputList
					.toArray(new AlarmConfiguration.AlarmOutput[0]);
		}
		alarmCfg.videoAlarm = (AlarmConfiguration.VideoAlarm[]) videoAlarmList
				.toArray(new AlarmConfiguration.VideoAlarm[0]);
		return alarmCfg;
	}


	public cn.com.sbell.vss.csg.vap.bean.DeviceInfo requestVsDeviceInfo() {
		DeviceCfg deviceCfg = new DeviceCfg();
		if (!HcNetAdapter.getDeviceCfg(userId, 0, deviceCfg)) {
		}

		cn.com.sbell.vss.csg.vap.bean.DeviceInfo deviceInfo = new cn.com.sbell.vss.csg.vap.bean.DeviceInfo();
		deviceInfo.setSoftWareVersion(deviceCfg.getFullSoftwareVersion());

		return deviceInfo;
	}

	public DeviceStatistic getVsWorkState() {
		WorkState workState = new WorkState();
		if (!HcNetAdapter.getWorkState(userId, workState)) {
		}
		DeviceStatistic ds = new DeviceStatistic();
		ds.setDeviceStatus(new Integer(workState.deviceStatus));
		ds.setRegisterStatus("" + workState.registerStatus);
		ds.setConnectionStatus("" + workState.connectionStatus);
		int MAX_DISKNUM = workState.disk.length;
		DeviceStatistic.DiskStatistic[] diskStat = new DeviceStatistic.DiskStatistic[MAX_DISKNUM];
		for (int i = 0; i < MAX_DISKNUM; i++) {
			diskStat[i] = new DeviceStatistic.DiskStatistic();
			diskStat[i].setDiskId(new Integer(i + 1));
			diskStat[i].setTotalSize(new Long(workState.disk[i].totalSize));
			diskStat[i].setFreeSize(new Long(workState.disk[i].freeSize));
		}
		ds.setDisk(diskStat);
		DeviceStatistic.VideoChannelStatistic[] videoStat = new DeviceStatistic.VideoChannelStatistic[deviceInfo.channelNum];
		for (int i = 0; i < deviceInfo.channelNum; i++) {
			videoStat[i] = new DeviceStatistic.VideoChannelStatistic();
			videoStat[i].setVideoId(new Integer(i + 1));
			videoStat[i].setRecordStatus(new Byte(
					workState.video[i].recordStatus));
			videoStat[i].setSignalStatus(new Byte(
					workState.video[i].signalStatus));
			videoStat[i].setHardwareStatus(new Byte(
					workState.video[i].hardwareStatus));
			videoStat[i].setBitRate(new Integer(
					workState.video[i].bitRate / 1000));
			videoStat[i].setCaptureStatus(new Byte(
					workState.video[i].captureStatus));
		}
		ds.setVideo(videoStat);
		byte[] alarmIn = new byte[deviceInfo.alarmInPortNum];
		System.arraycopy(workState.alarmIn, 0, alarmIn, 0, alarmIn.length);
		ds.setAlarmIn(alarmIn);
		byte[] alarmOut = new byte[deviceInfo.alarmOutPortNum];
		System.arraycopy(workState.alarmOut, 0, alarmOut, 0, alarmOut.length);
		ds.setAlarmOut(alarmOut);

		return ds;
	}

	public boolean setDeviceId(String id) {
		FrontIdCfg frontIdCfg = new FrontIdCfg();
		try {
			frontIdCfg.frontId = id.getBytes(HikVisionDVRClient.CHARSET);
		} catch (UnsupportedEncodingException e) {
			System.out.println("Set device id error!" + e);
		}
		return HcNetAdapter.setFrontIdCfg(userId, frontIdCfg);
	}

	public CameraHide getHideImageArea(int cameraNumber) {
		HideImageAreaCfg hcHideImageAreaCfg = new HideImageAreaCfg();
		if (!HcNetAdapter.getHideImageAreaCfg(userId, cameraNumber,
				hcHideImageAreaCfg)) {
		}

		CameraHide cameraHide = new CameraHide();
		cameraHide.setCameraNumber(new Integer(cameraNumber));

		HideImageArea[] hcHideImageAreas = hcHideImageAreaCfg.hideImageAreas;
		List temp = new ArrayList();
		for (int i = 0; i < hcHideImageAreas.length; i++) {
			CameraHide.HideImageArea hideImageArea = cameraHide.new HideImageArea();
			hideImageArea.setX(new Integer(
					hcHideImageAreas[i].hideImageAreaTopLeftX));
			hideImageArea.setY(new Integer(
					hcHideImageAreas[i].hideImageAreaTopLeftY));
			hideImageArea.setWidth(new Integer(
					hcHideImageAreas[i].hideImageAreaWidth));
			hideImageArea.setHeight(new Integer(
					hcHideImageAreas[i].hideImageAreaHeight));
			temp.add(hideImageArea);
		}
		cameraHide.setHideImageAreas((CameraHide.HideImageArea[]) temp
				.toArray(new CameraHide.HideImageArea[0]));
		return cameraHide;
	}

	public boolean setHideImageArea(CameraHide cameraHide) {
		HideImageAreaCfg hcHideImageAreaCfg = new HideImageAreaCfg();
		if (!HcNetAdapter.getHideImageAreaCfg(userId, cameraHide
				.getCameraNumber().intValue(), hcHideImageAreaCfg)) {
			return false;
		}

		hcHideImageAreaCfg.enableHide = 0;
		CameraHide.HideImageArea[] hideImageAreas = cameraHide
				.getHideImageAreas();
		if (hideImageAreas.length > 0 && hideImageAreas.length <= 4) {
			hcHideImageAreaCfg.enableHide = 1;
			List temp = new ArrayList();
			for (int i = 0; i < hideImageAreas.length; i++) {
				HideImageArea hcHideImageArea = new HideImageArea();
				hcHideImageArea.hideImageAreaTopLeftX = hideImageAreas[i]
						.getX().intValue();
				hcHideImageArea.hideImageAreaTopLeftY = hideImageAreas[i]
						.getY().intValue();
				hcHideImageArea.hideImageAreaHeight = hideImageAreas[i]
						.getHeight().intValue();
				hcHideImageArea.hideImageAreaWidth = hideImageAreas[i]
						.getWidth().intValue();
				temp.add(hcHideImageArea);
			}
			if (hideImageAreas.length < 4) { // Max HideImageArea: 4
				for (int i = 0; i < 4 - hideImageAreas.length; i++) {
					HideImageArea hcHideImageArea = new HideImageArea();
					hcHideImageArea.hideImageAreaTopLeftX = 0;
					hcHideImageArea.hideImageAreaTopLeftY = 0;
					hcHideImageArea.hideImageAreaHeight = 0;
					hcHideImageArea.hideImageAreaWidth = 0;
					temp.add(hcHideImageArea);
				}
			}
			hcHideImageAreaCfg.hideImageAreas = (HideImageArea[]) temp
					.toArray(new HideImageArea[0]);
		}

		return HcNetAdapter.setHideImageAreaCfg(userId, cameraHide
				.getCameraNumber().intValue(), hcHideImageAreaCfg);
	}

	public boolean setNetManageInfo(NetManageInfo netManageInfo) {
		ManageCfg manageCfg = new ManageCfg();
		try {
			if (null != netManageInfo.getHeartBeatServerIp()) {
				if (!"192.168.6.75".equals(netManageInfo.getHeartBeatServerIp())) {
					System.out.println("[heartBeatServerIp!=vs.common.heartbeat.report.ipaddress]\n");
					System.out.println("heartBeatServerIp="
							+ netManageInfo.getHeartBeatServerIp()
							+ "&& vs.common.heartbeat.report.ipaddress="
							+ "192.168.6.75"
							+ "\n");
				}
				manageCfg.heartBeatServerIp = netManageInfo
						.getHeartBeatServerIp().getBytes(
								HikVisionDVRClient.CHARSET);
			}
			if (null != netManageInfo.getRegisterServerIp()) {
				if (!"192.168.6.75".equals(netManageInfo.getRegisterServerIp())) {
					System.out.println("[registerServerIp!=vs.common.heartbeat.report.ipaddress]\n");
					System.out.println("registerServerIp="
							+ netManageInfo.getRegisterServerIp()
							+ "&& vs.common.heartbeat.report.ipaddress="
							+ "192.168.6.75"
							+ "\n");
				}
				manageCfg.registerServerIp = netManageInfo
						.getRegisterServerIp().getBytes(
								HikVisionDVRClient.CHARSET);
			}
		} catch (UnsupportedEncodingException e) {
			System.out.println("setNetManageInfo failded" + e);
			return false;
		}
		if (null != netManageInfo.getEnableHeartBeat()) {
			manageCfg.heartBeatEnable = netManageInfo.getEnableHeartBeat()
					.booleanValue();
		}
		if (null != netManageInfo.getHeartBeatPort()) {
			if (10002 != netManageInfo
					.getHeartBeatPort().intValue()) {
				System.out.println("[heartBeatPort!=vs.common.heartbeat.report.port]\n");
				System.out.println("heartBeatPort="
						+ netManageInfo.getHeartBeatPort().intValue()
						+ "&& vs.common.heartbeat.report.port="
						+ 10002 + "\n");
			}
			manageCfg.heartBeatServerPort = netManageInfo.getHeartBeatPort()
					.intValue();
		}
		if (null != netManageInfo.getHeartBeatPeriod()) {
			if (60 != netManageInfo
					.getHeartBeatPeriod().intValue()) {
				System.out.println("[heartBeatPeriod!=vs.common.heartbeat.report.interval]\n");
				System.out.println("heartBeatPeriod="
						+ netManageInfo.getHeartBeatPeriod().intValue()
						+ "&& vs.common.heartbeat.report.interval="
						+ 60 + "\n");
			}
			manageCfg.interval = netManageInfo.getHeartBeatPeriod().intValue();
		}
		if (null != netManageInfo.getRegisterPort()) {
			if (10002 != netManageInfo
					.getRegisterPort().intValue()) {
				System.out.println("[registerPort!=vs.common.heartbeat.report.port]\n");
				System.out.println("registerPort=" + netManageInfo.getRegisterPort()
						+ "&& vs.common.heartbeat.report.port="
						+ 10002 + "\n");
			}
			manageCfg.registerPort = netManageInfo.getRegisterPort().intValue();
		}
		if (null != netManageInfo.getRegisterValidTime()) {
			if (120000 != netManageInfo
					.getRegisterValidTime().intValue()) {
				System.out.println("[registerDuration!=vs.common.heartbeat.life]\n");
				System.out.println("registerDuration="
						+ netManageInfo.getRegisterValidTime()
						+ "&& vs.common.heartbeat.life="
						+ 120000 + "\n");
			}
			manageCfg.registerDuration = netManageInfo.getRegisterValidTime()
					.intValue();
		}

		if (!HcNetAdapter.setManageCfg(userId, manageCfg)) {
			return false;
		}

		//
		NetCfg netCfg = new NetCfg();
		if (!HcNetAdapter.getNetCfg(userId, -1, netCfg)) {
			return false;
		}
		if (null != netManageInfo.getManagerServerIp()) {
			if (!"192.168.6.75".equals(netManageInfo.getManagerServerIp())) {
				System.out.println("[managerServerIp!=vs.common.alarm.report.ipaddress]\n");
				System.out.println("managerServerIp="
						+ netManageInfo.getManagerServerIp()
						+ "&& vs.common.alarm.report.ipaddress="
						+ "192.168.6.75" + "\n");
			}
			netCfg.manageHostIp = netManageInfo.getManagerServerIp();
		}
		if (null != netManageInfo.getManagerServerPort()) {
			if (10001 != netManageInfo
					.getManagerServerPort().intValue()) {
				System.out.println("[managerServerPort!=vs.hikvision.alarm.report.port]\n");
				System.out.println("managerServerPort="
						+ netManageInfo.getManagerServerPort()
						+ "&& vs.hikvision.alarm.report.port="
						+ 10001 + "\n");
			}
			netCfg.manageHostPort = netManageInfo.getManagerServerPort()
					.intValue();
		}
		if (!HcNetAdapter.setNetCfg(userId, -1, netCfg)) {
			return false;
		}

		this.controlVs(0);
		return true;
	}	
	
	public NetManageInfo getNetManageInfo() {
		NetManageInfo netManageInfo = new NetManageInfo();
		NetCfg netCfg = new NetCfg();
		if (!HcNetAdapter.getNetCfg(userId, -1, netCfg)) {
			System.out.println("HcNetAdapter.getNetCfg failed...");
		}else{
			System.out.println(netCfg.dns);
			System.out.println(netCfg.gateway);
			System.out.println(netCfg.manageHostIp);
			System.out.println(netCfg.manageHostPort);
			for (int i = 0; i < netCfg.ethernet.length; i++) {
				System.out.println(netCfg.ethernet[i].ipAddress);
				System.out.println(netCfg.ethernet[i].netMask);
				System.out.println(netCfg.ethernet[i].port);
			}
		}
		
		ManageCfg manageCfg = new ManageCfg();
		if (!HcNetAdapter.getManageCfg(userId, manageCfg)) {
			System.out.println("HcNetAdapter.getManageCfg failed...");
		}else{
			System.out.println(manageCfg.heartBeatEnable);
			System.out.println(new String(manageCfg.heartBeatServerIp));
			System.out.println(manageCfg.heartBeatServerPort);
			System.out.println(manageCfg.interval);
			System.out.println(new String(manageCfg.registerServerIp));
			System.out.println(manageCfg.registerPort);
			System.out.println(manageCfg.registerDuration);
		}
		
		netManageInfo.setEnableHeartBeat(Boolean
				.valueOf(manageCfg.heartBeatEnable));
		netManageInfo.setHeartBeatPeriod(new Integer(manageCfg.interval));
		netManageInfo.setHeartBeatPort(new Integer(
				manageCfg.heartBeatServerPort));
		try {
			netManageInfo.setHeartBeatServerIp(new String(
					manageCfg.heartBeatServerIp, HikVisionDVRClient.CHARSET));
			netManageInfo.setRegisterServerIp(new String(
					manageCfg.registerServerIp, HikVisionDVRClient.CHARSET));
		} catch (UnsupportedEncodingException e) {
			System.out.println("getNetManageInfo failed" + e);
		}
		netManageInfo.setManagerServerIp(netCfg.manageHostIp);
		netManageInfo.setManagerServerPort(new Integer(netCfg.manageHostPort));
		netManageInfo.setRegisterPort(new Integer(manageCfg.registerPort));
		netManageInfo.setRegisterValidTime(new Integer(
				manageCfg.registerDuration));

		return netManageInfo;
	}

	public VSCommon getVSCommon() {
		VsCommonInfo vsCommonInf = new VsCommonInfo();
		VSCommon vsCommon = new VSCommon();
		FrontIdCfg frontIdCfg = new FrontIdCfg();
		if (!HcNetAdapter.getFrontIdCfg(userId, frontIdCfg)) {
		}
		if (!HcNetAdapter.getVsCommonInf(userId, 0, vsCommonInf)) {
		}

		vsCommon.setDeviceId(new String(frontIdCfg.frontId));
		vsCommon.setDeviceName(new String(vsCommonInf.dvrName));
		vsCommon.setVideoMonitorEnabled(Boolean
				.toString((vsCommonInf.videoMonitorEnabled == 1)));
		vsCommon.setVideoMonitorInterval(new Integer(
				vsCommonInf.videoMonitorInterval));
		vsCommon.setPassWord(new String(vsCommonInf.devRegPasswd));
		return vsCommon;
	}

	public boolean setVSCommon(VSCommon commonInfo) {
		VsCommonInfo vsCommonInf = new VsCommonInfo();
		if (!HcNetAdapter.getVsCommonInf(userId, 0, vsCommonInf)) {
		}
		try {
			if (null != commonInfo.getDeviceName()) {
				vsCommonInf.dvrName = commonInfo.getDeviceName().getBytes(
						HikVisionDVRClient.CHARSET);
			}
			if (null != commonInfo.getPassWord()) {
				vsCommonInf.devRegPasswd = commonInfo.getPassWord().getBytes(
						HikVisionDVRClient.CHARSET);
			}
		} catch (Exception e) {
			System.out.println("getNetManageInfo failed" + e);
		}

		if (null != commonInfo.getVideoMonitorEnabled()) {
			vsCommonInf.videoMonitorEnabled = commonInfo
					.getVideoMonitorEnabled().equalsIgnoreCase("true") ? 1 : 0;
		}
		if (null != commonInfo.getVideoMonitorInterval()) {
			vsCommonInf.videoMonitorInterval = commonInfo
					.getVideoMonitorInterval().intValue();
		}

		if (!setDeviceId(commonInfo.getDeviceId())) {
		}
		if (!HcNetAdapter.setVsCommonInf(userId, 0, vsCommonInf)) {
		}
			System.out.println("java:videoMonitorEnabled:"
					+ vsCommonInf.videoMonitorEnabled + ",videoMonitorInterval"
					+ vsCommonInf.videoMonitorInterval);
		return true;
	}

	public boolean recordVideo(Integer[] videoIds, Integer duration) {
		RecordStatus rs = new RecordStatus();
		for (int i = 0; i < videoIds.length; i++) {
			if (videoIds[i] > deviceInfo.channelNum + deviceInfo.startChannel) {
			}
		}
		rs.byChans = new byte[deviceInfo.channelNum];
		rs.dwRecTime = new int[deviceInfo.channelNum];
		for (int i = 0; i < videoIds.length; i++) {
			rs.byChans[videoIds[i] - 1] = 1;
			rs.dwRecTime[videoIds[i] - 1] = duration.intValue();
		}
		return HcNetAdapter.startRecord(userId, rs);

	}

	public VideoPerformance getVsPerformance(String statisticTarget) {
		VideoPerformance videoPerformance = new VideoPerformance();
		ResourceUsedInfo resourceUsedInfo = new ResourceUsedInfo();
		if (!HcNetAdapter.getResourceUsedInfo(userId, 0, resourceUsedInfo)) {
		}
		videoPerformance.setCpu(String.valueOf(resourceUsedInfo.cpuUsed));
		videoPerformance.setMemory(String.valueOf(resourceUsedInfo.memoryUsed));
		videoPerformance.setDisk(String.valueOf(resourceUsedInfo.diskUsed));
		videoPerformance.setTimestamp(resourceUsedInfo.timeStamp);
		return videoPerformance;
	}

	public AlarmConfiguration getVsAlarmConfiguration() {
		AlarmConfiguration alarmConfiguration = new AlarmConfiguration();
		// connectionDetection
		ManageCfg manageCfg = new ManageCfg();
		if (!HcNetAdapter.getManageCfg(userId, manageCfg)) {
			return null;
		}
		alarmConfiguration.connectionDetectionEnabled = manageCfg.heartBeatEnable;
		ExceptionCfg exceptionCfg = new ExceptionCfg();
		if (!HcNetAdapter.getExceptionCfg(userId, 0, exceptionCfg)) {
			System.out.println("GetVsAlarmConfiguration getExceptionCfg fail");
			return null;
		}
		alarmConfiguration.diskErrorAlarmEnabled = exceptionCfg.diskErrorEnable;
		alarmConfiguration.diskFullAlarmEnabled = exceptionCfg.diskFullEnable;
		for (int i = 0; i < deviceInfo.alarmOutPortNum; i++) {
			AlarmOutCfg alarmOutCfg = new AlarmOutCfg();
			if (!HcNetAdapter.getAlarmOutCfg(userId, i, alarmOutCfg)) {
				System.out.println("SetVsAlarmConfiguration getAlarmOutCfg fail");
				return null;
			}
			alarmConfiguration.alarmOutputTime = -1;
			if (-1 != alarmOutCfg.delay) {
				alarmConfiguration.alarmOutputTime = alarmOutCfg.delay;
			}
		}
		// System.out.println("GetVsAlarmConfiguraton processed getExceptionCfg");
		for (int i = deviceInfo.startChannel; i < deviceInfo.startChannel
				+ deviceInfo.channelNum; i++) {// record equal to number
			RecordCfg recordCfg = new RecordCfg();
			// changed vondart
			// System.out.println("getRecordCfg for channel:"+i);
			if (!HcNetAdapter.getRecordCfg(userId, i, recordCfg)) {
				System.out.println("GetVsAlarmConfiguration getRecordCfg fail");
				return null;
			}
			if ((null != recordCfg.recordAllDay)
					&& (recordCfg.recordAllDay.length >= 1)
					&& (recordCfg.recordAllDay[0].recordAllDayEnable == 1)) {
				alarmConfiguration.alarmPreRecordTime = recordCfg.preRecordTime;
				alarmConfiguration.alarmRecordTime = recordCfg.recordTime;
				break;
			}
		}
		// System.out.println("GetVsAlarmConfiguraton processed getRecordCfg");
		JPEGCFG jpegCfg = new JPEGCFG();
		int[] triggeredCap = null;
		if (!HcNetAdapter.getJPEGCFG(userId, jpegCfg)) {
			System.out.println("GetVsAlarmConfiguration getJPEGCfg fail");
			fillInJPEGCFG(jpegCfg);
			// modified by vondart to accomodate dvs without alarm shoot
			// return null;
		}
		triggeredCap = jpegCfg.dwAlarmInPicChanTriggered;

		alarmConfiguration.shootTimes = jpegCfg.dwTriggerPicTimes[0];
		int temp = jpegCfg.struJpegPara[0].wPicSize;
		switch (temp) {
		case 1:
			alarmConfiguration.photoResolution = 0;
			break;
		case 0:
			alarmConfiguration.photoResolution = 1;
			break;
		default:
			alarmConfiguration.photoResolution = temp;
			break;

		}
		alarmConfiguration.photoQuality = jpegCfg.struJpegPara[0].wPicQuality;

		// System.out.println("GetVsAlarmConfiguraton processed getJPEGCfg");
		AlarmConfiguration.GPINAlarm[] gpincfgs = new AlarmConfiguration.GPINAlarm[deviceInfo.alarmInPortNum];
		for (int i = 0; i < deviceInfo.alarmInPortNum; i++) {// channel start
																// from 0
			AlarmInCfg alarmInCfg = new AlarmInCfg();
			// System.out.println("getAlarmInCfg for channel:"+i);
			if (!HcNetAdapter.getAlarmInCfg(userId, i, alarmInCfg)) {
				System.out.println("GetVsAlarmConfiguration getAlarmInCfg fail");
				return null;
			}
			AlarmConfiguration.GPINAlarm gpincfg = new AlarmConfiguration.GPINAlarm();
			// channer number starts from 1;
			gpincfg.channelNumber = i + 1;
			gpincfg.gpinAlarmEnable = (alarmInCfg.alarmInHandle == 1);
			gpincfg.gpinAlarmStatus = alarmInCfg.state;
			ArrayList alarmOutput = new ArrayList();
			int[] alarmOut = parseIntArray(alarmInCfg.alarmOut);
			for (int j = 0; j < alarmOut.length; j++) {
				AlarmConfiguration.AlarmOutput output = new AlarmConfiguration.AlarmOutput();
				output.channelNumber = alarmOut[j];
				output.alarmState = alarmInCfg.state;
				alarmOutput.add(output);
			}
			gpincfg.gpinAlarmOutput = (AlarmConfiguration.AlarmOutput[]) alarmOutput
					.toArray(new AlarmConfiguration.AlarmOutput[0]);
			gpincfg.gpinAlarmRecord = parseIntArray(alarmInCfg.alarmRecordChannel);
			gpincfg.gpinAlarmShoot = parseBit(triggeredCap[i]);
			gpincfgs[i] = gpincfg;
		}
		// System.out.println("GetVsAlarmConfiguraton processed getAlarmInCfg");
		AlarmConfiguration.GPOUTAlarm[] gpoutcfgs = new AlarmConfiguration.GPOUTAlarm[deviceInfo.alarmOutPortNum];
		for (int i = 0; i < deviceInfo.alarmOutPortNum; i++) {
			AlarmConfiguration.GPOUTAlarm gpoutcfg = new AlarmConfiguration.GPOUTAlarm();
			gpoutcfg.channelNumber = i + 1;
			gpoutcfg.gpoutDeviceName = "";
			gpoutcfg.gpoutType = 0;
			Schedule schedule = new Schedule();
			schedule.setStartHour(0);
			schedule.setStartMin(0);
			schedule.setStopHour(24);
			schedule.setStopMin(0);
			gpoutcfg.gpoutActivatedTime = schedule;
			gpoutcfgs[i] = gpoutcfg;
		}
		// System.out.println("GetVsAlarmConfiguraton processed getAlarmOutCfg");
		AlarmConfiguration.VideoAlarm[] cameraAlarm = new AlarmConfiguration.VideoAlarm[deviceInfo.channelNum];
		for (int i = deviceInfo.startChannel; i < deviceInfo.startChannel
				+ deviceInfo.channelNum; i++) {// channel start from 1, end <=
			PicCfg picCfg = new PicCfg();
			// System.out.println("getPicCfg for channel:"+i);
			if (!HcNetAdapter.getPicCfg(userId, i, picCfg)) {
				System.out.println("GetVsAlarmConfiguration getPicCfg fail");
				return null;
			}
			// System.out.println("GetVsAlarmConfiguraton begin processing getPicCfg for channel"+i);
			AlarmConfiguration.VideoAlarm videoAlarm = new AlarmConfiguration.VideoAlarm();
			videoAlarm.videoId = i;
			videoAlarm.videoLoseAlarmEnabled = (picCfg.videoLoseAlarmEnabled == 1);
			ArrayList alarmOutput = new ArrayList();
			int[] alarmOut = parseIntArray(picCfg.videoLoseAlarmOut);
			for (int j = 0; j < alarmOut.length; j++) {
				AlarmConfiguration.AlarmOutput output = new AlarmConfiguration.AlarmOutput();
				output.channelNumber = alarmOut[j];
				alarmOutput.add(output);
			}
			videoAlarm.videoLoseAlarmOutput = (AlarmConfiguration.AlarmOutput[]) alarmOutput
					.toArray(new AlarmConfiguration.AlarmOutput[0]);
			// System.out.println("GetVsAlarmConfiguraton finish processing video lose for channel"+i);

			videoAlarm.hideDetectionAlarmEnabled = (picCfg.hideAlarmEnable == 1);

			Schedule time = new Schedule();
			time.setStartHour(picCfg.hideAlarmTime[0][0].startHour);
			time.setStartMin(picCfg.hideAlarmTime[0][0].startMin);
			time.setStopHour(picCfg.hideAlarmTime[0][0].stopHour);
			time.setStopMin(picCfg.hideAlarmTime[0][0].stopMin);
			videoAlarm.hideDetectionAlarmTime = time;
			videoAlarm.hideDetectionX = picCfg.hideAlarmAreaTopLeftX;
			videoAlarm.hideDetectionY = picCfg.hideAlarmAreaTopLeftY;
			videoAlarm.hideDetectionHeight = picCfg.hideAlarmAreaHeight;
			videoAlarm.hideDetectionWidth = picCfg.hideAlarmAreaWidth;
			ArrayList hideOutput = new ArrayList();
			int[] hideOut = parseIntArray(picCfg.hideAlarmOut);
			for (int j = 0; j < hideOut.length; j++) {
				AlarmConfiguration.AlarmOutput output = new AlarmConfiguration.AlarmOutput();
				output.channelNumber = hideOut[j];
				hideOutput.add(output);
			}
			videoAlarm.hideDetectionAlarmOutput = (AlarmConfiguration.AlarmOutput[]) hideOutput
					.toArray(new AlarmConfiguration.AlarmOutput[0]);
			// System.out.println("GetVsAlarmConfiguraton begin process hide detection output for channel"+i);
			videoAlarm.motionDetectionAlarmEnabled = (picCfg.motionAlarmEnable == 1);
			Schedule time2 = new Schedule();
			time2.setStartHour(picCfg.motionAlarmTime[0][0].startHour);
			time2.setStartMin(picCfg.motionAlarmTime[0][0].startMin);
			time2.setStopHour(picCfg.motionAlarmTime[0][0].stopHour);
			time2.setStopMin(picCfg.motionAlarmTime[0][0].stopMin);
			videoAlarm.motionDetectionAlarmTime = time2;
			// System.out.println("GetVsAlarmConfiguraton begin process time for channel"+i);
			int len = 0;
			for (int l = 0; l < picCfg.motionScope.length; l++) {
				len += picCfg.motionScope[l].length;
			}
			int count = 0;
			byte[] motionScope = new byte[len];
			// changed from motionScope from i to k
			for (int k = 0; k < picCfg.motionScope.length; k++) {
				for (int j = 0; j < picCfg.motionScope[k].length; j++) {

					motionScope[count++] = picCfg.motionScope[k][j];
				}
			}
			videoAlarm.motionDetectionBlocks = motionScope;
			// System.out.println("GetVsAlarmConfiguraton begin process block for channel"+i);
			videoAlarm.motionDetectionSensitivity = picCfg.montionSenstive;
			ArrayList motionOutput = new ArrayList();
			int[] motionOut = parseIntArray(picCfg.motionAlarmOut);
			for (int j = 0; j < motionOut.length; j++) {
				AlarmConfiguration.AlarmOutput output = new AlarmConfiguration.AlarmOutput();
				output.channelNumber = motionOut[j];
				motionOutput.add(output);
			}
			videoAlarm.motionDetectionAlarmOutput = (AlarmConfiguration.AlarmOutput[]) motionOutput
					.toArray(new AlarmConfiguration.AlarmOutput[0]);
			// System.out.println("GetVsAlarmConfiguraton begin process motionDetectionAlarmOutput for channel"+i);
			// System.out.println("motionRecordChannel:"+Arrays.toString(picCfg.motionRecordChannel));
			videoAlarm.motionDetectionAlarmRecord = parseIntArray(picCfg.motionRecordChannel);
			System.out.println("motion detect shoot:hanle type["
					+ Integer.toHexString(picCfg.motionHandleType)
					+ "],burst mode[" + Integer.toHexString(jpegCfg.wBurstMode)
					+ "]");
			if (((picCfg.motionHandleType & 0x20) == 0x20)
					&& ((jpegCfg.wBurstMode & 0x2) == 0x2)) {
				videoAlarm.motionDetectionAlarmShoot = new int[] { i };
			}

			// why start from 0?
			cameraAlarm[i - deviceInfo.startChannel] = videoAlarm;

			// System.out.println("GetVsAlarmConfiguraton begin processed motion detection for channel"+i);
		}
		// System.out.println("GetVsAlarmConfiguraton processed getAlarmInCfg");
		alarmConfiguration.gpinAlarm = gpincfgs;
		alarmConfiguration.videoAlarm = cameraAlarm;
		// temporarily commented
		alarmConfiguration.imageFormat = new String("JPEG");
		//
		ImageFormat imageFormat = new ImageFormat();
		if (!HcNetAdapter.getImageFormat(userId, 0, imageFormat)) {
			System.out.println("GetVsAlarmConfiguration getImageFormat fail");
			return null;
		}
		alarmConfiguration.imageFormat = new String(imageFormat.imageFormate)
				.trim();
		System.out.println(alarmConfiguration);
		return alarmConfiguration;
	}

	public int GetVsPPPoEPeriod() {
		PPPoEConf conf = new PPPoEConf();
		if (!HcNetAdapter.getPPPoEPeriod(userId, conf)) {
			System.out.println("GetVsPPPoE failed");
			return 0;
		}
		return conf.validDays;
	}

	public boolean SetVsPPPoEPeriod(int validDays) {
		PPPoEConf conf = new PPPoEConf();
		conf.validDays = validDays;
		if (!HcNetAdapter.setPPPoEPeriod(userId, conf)) {
			System.out.println("SetVsPPPoE failed");
			return false;
		}
		return true;
	}

	public boolean SetVsLogPrint(int isPrint) {
		if (!HcNetAdapter.SetVsLogPrint(isPrint)) {
			System.out.println("SetVsLogPrint failed");
			return false;
		}
		return true;
	}

	public UploadPic getUploadPicture(String deviceId) {
		cn.com.sbell.vss.csg.vsclient.hikvision.bean.UploadPic up = new cn.com.sbell.vss.csg.vsclient.hikvision.bean.UploadPic();
		if (!HcNetAdapter.getUploadPicture(userId, up)) {
			System.out.println("get upload picture error");
		}
		UploadPic u = new UploadPic();
		try {
			u.setUploadURL(new String(up.byPicUrl, CHARSET));
			u.setEnableUploadPicture(up.wEnablePicUp == 1 ? true : false);
			u.setLimitedAmount(up.wPicCount);
			u.setLimitedResolution(up.wPicResolution);
			u.setWaitingTimeAfterfailure(up.wPicWaitTime);
		} catch (Exception e) {
			System.out.println("get upload picture error");
		}

		return u;
	}

	public boolean setUploadPicture(UploadPic up) {
		cn.com.sbell.vss.csg.vsclient.hikvision.bean.UploadPic p = new cn.com.sbell.vss.csg.vsclient.hikvision.bean.UploadPic();
		try {
			p.byPicUrl = up.getUploadURL().getBytes(CHARSET);
			p.wEnablePicUp = up.isEnableUploadPicture() ? 1 : 0;
			p.wPicCount = up.getLimitedAmount();
			p.wPicResolution = up.getLimitedResolution();
			p.wPicWaitTime = up.getWaitingTimeAfterfailure();

		} catch (Exception e) {
			System.out.println("invalid char" + e);
		}

		if (!HcNetAdapter.setUploadPicture(userId, p)) {
			System.out.println("get upload picture error");
		}
		return true;
	}

	public PTZRegress getPTZRegress(int ptzId) {
		PTZResetCfg reset = new PTZResetCfg();
		if (!HcNetAdapter.getPTZPreset(userId, reset, ptzId)) {
		}
		PTZRegress res = new PTZRegress();
		res.setEnableRegress(reset.dwResetEnable == 1 ? true : false);
		res.setPtzId(ptzId);
		res.setPresetIndex(reset.dwPosition);
		res.setRegressTime(reset.dwTime);
		res.setPresetName("");
		return res;
	}

	public boolean setPTZRegress(PTZRegress ptzregress) {
		PTZResetCfg reset = new PTZResetCfg();
		reset.dwPosition = ptzregress.getPresetIndex();
		reset.dwResetEnable = ptzregress.isEnableRegress() ? 1 : 0;
		reset.dwTime = ptzregress.getRegressTime();

		return HcNetAdapter.setPTZPreset(userId, reset, ptzregress.getPtzId());
	}

	// -------------------------------PHASE 2 END
	// ----------------------------------
	// ///////////////////////////////////////////
	// UTILITY METHOD
	// ///////////////////////////////////////////
	private final static int[] BAUDRATE = { 50, 75, 110, 150, 300, 600, 1200,
			2400, 4800, 9600, 19200, 38400, 57600, 76800, 115200 };

	private static int getVapBaudRate(int hcValue) {
		return BAUDRATE[hcValue];
	}

	private static int getHcBaudRate(int vapValue) {
		int hcValue = Arrays.binarySearch(BAUDRATE, vapValue);
		if (hcValue < 0) {
			return (-hcValue - 2) < 0 ? 0 : (-hcValue - 2);
		} else {
			return hcValue;
		}
	}

	private final static int[] BITRATE = { -1, 16, 32, 48, 64, 80, 96, 128,
			160, 192, 224, 256, 320, 384, 448, 512, 640, 768, 896, 1024, 1280,
			1536, 1792, 2048 };

	private static int getVapBitRate(int hcBitRate) {
		int vapValue;
		if (hcBitRate > 0) {
			vapValue = BITRATE[hcBitRate];
		} else {
			vapValue = (0x7FFFFFFF & hcBitRate) / 1000;
		}
		return vapValue;
	}

	private static int getHcBitRate(int vapBitRate) {
		return 0x80000000 | (vapBitRate * 1000);
	}

	private final static int[] FRAMERATE = { 16000, 8000, 4000, 2000, 1000,
			500, 250, 166, 125, 100, 83, 62, 50, 40, 0 };

	private static int getVapFrameRate(int hcFrameRate) {
		if (hcFrameRate == 0) {
			return 40; // full framerate
		} else if (hcFrameRate < 5 || hcFrameRate > 13) {
			return -1; // error result;
		}
		return FRAMERATE[hcFrameRate - 1];
	}

	private static int getHcFrameRate(int vapFrameRate) {
		if (vapFrameRate >= 1000) {
			return 5;
		} else if (vapFrameRate <= 40) {
			return 0;
		}
		int i = 0;
		for (; i < FRAMERATE.length; i++) {
			if (FRAMERATE[i] < vapFrameRate)
				break;
		}
		return i;
	}

	private int[] toIntArray(List list) {
		int[] result = new int[list.size()];
		int i = 0;
		for (Iterator iter = list.iterator(); iter.hasNext(); i++) {
			result[i] = ((Integer) iter.next()).intValue();
		}
		return result;
	}

	private int[] parseIntArray(byte[] in) {
		int[] result = new int[in.length];
		int count = 0;
		for (int i = 0; i < in.length; i++) {
			if (in[i] == 1) {
				result[count++] = i + 1;
			}
		}
		int[] finalResult = new int[count];
		System.arraycopy((Object) result, 0, (Object) finalResult, 0, count);
		return finalResult;
	}

	private int[] parseBit(int in) {
		int temp = 0x1;
		int count = 0;
		int[] result = new int[Integer.SIZE];
		for (int i = 0; i < Integer.SIZE; i++) {
			if ((in & temp) == temp) {
				result[count++] = i;
			}
			temp <<= 1;
		}
		int[] finalResult = new int[count];
		System.arraycopy((Object) result, 0, (Object) finalResult, 0, count);
		return finalResult;
	}

	private byte[] setIfNotNull(String src) {
		if (null != src) {
			return src.getBytes();
		} else {
			return null;
		}

	}

	private boolean setIfNotNullAndEqual(String src, String dest) {
		if (null != src) {
			return dest.equalsIgnoreCase(src);
		}
		return false;
	}

	private int calTime(int s) {
		return 0;
	}

	private void fillInJPEGCFG(JPEGCFG jpegCfg) {
		JPEGPARA jpegPara = new JPEGPARA();
		jpegPara.wPicQuality = 0;
		jpegPara.wPicSize = 0;
		jpegCfg.dwAlarmInPicChanTriggered = new int[deviceInfo.alarmInPortNum];
		Arrays.fill(jpegCfg.dwAlarmInPicChanTriggered, 1);
		jpegCfg.dwTriggerPicTimes = new int[] { 1 };
		jpegCfg.struJpegPara = new JPEGPARA[] { jpegPara };
		jpegCfg.wBurstMode = 0x1;

	}
	// class RecordVideoThread extends Thread{
	// private Integer[] videoIds;
	// private Integer duration;
	// public RecordVideoThread(Integer[] videoIds,Integer duration) {
	// super();
	// this.videoIds = videoIds;
	// this.duration=duration;
	// }
	//
	// @Override
	// public void run() {
	// int recordVideoUserId=-1;
	// DeviceInfo recordVideoDeviceInfo=new DeviceInfo();
	// try {
	// recordVideoUserId = HcNetAdapter.login(access.vsIp,
	// access.vsPort.intValue(), access.vsLoginUsername, access.vsLoginPassword,
	// recordVideoDeviceInfo);
	// } catch (Exception e) {
	// System.out.println("start record failed, can't login" + e);
	// return;
	// }
	// if(-1==recordVideoUserId){
	// System.out.println("start record failed, can't login");
	// return;
	// }
	// for (int i = 0; i < videoIds.length; i++) {
	// try {
	// HcNetAdapter.startRecord(recordVideoUserId, videoIds[i], duration);
	// } catch (Exception e) {
	// System.out.println("start record failed for channel:"+videoIds[i], e);
	// }
	// }
	// try {
	// if(recordVideoUserId >=0){
	// HcNetAdapter.logout(recordVideoUserId);
	// }
	// } catch (Exception e) {
	// System.out.println("start record finished, can't logout" + e);
	// return;
	// }
	// }
	//
	// }
}
